perm filename TANOLD.WEB[WEB,ALS] blob
sn#628248 filedate 1981-12-10 generic text, type T, neo UTF8
% Here is TEX material that gets inserted after \input webhdr
\def\hang{\hangindent 3em\ \unskip\!}
\def\TEX{\hbox{T\hskip-.1667em\lower.424ex\hbox{E}\hskip-.125em X}}
\font b=cmr9 \def\mc{\:b} % medium caps for names like PASCAL
\def\PASCAL{{\mc PASCAL}}
\def\pb{$\.|\ldotsm\.|$} % pascal brackets (|...|)
\def\v{\.{\char'174}} % vertical (|) in typewriter font
\def\at{@@} % at sign to use in control text
\def\({} % kludge for alphabetizing certain module names
\font D=cmtt at 15truept % font used in the title line below (only)
\font E=cmr7 at 14truept % font used in the title line below (only)
\def\title{TANGLE}
\def\contentspagenumber{108}
\def\topofcontents{\hbox to size{\:a Appendix E\hfil \count0}
\vfill
\ctrline{\:E The {\:D TANGLE} processor}
\vskip 15pt
\ctrline{(preliminary version, November 1981)}
\vfill}
\def\botofcontents{\vfill
\ctrline{\ragged0\spaceskip0pt\xspaceskip0pt\baselineskip9pt
\hbox par 5in{\:bThis copy of the program is
being distributed to interested ``guinea pigs'' before it has
been thoroughly tested, in order to get extra help in the testing
process. It is expected that changes will be made frequently
while \TEX82 is being developed in the next months. Several
comments in this documentation imply that the program has
already been applied successfully to \TEX; such remarks are
merely wishful thinking at this point, but they will be true
when the final version is completed.}}}
\setcount0 \contentspagenumber
\topofcontents
\ctrline{(replace this page by the contents page printed later)}
\botofcontents
\mark{1}\eject
@* Introduction.
This program converts a \.{WEB} file to a \PASCAL\ file. It was written
by D. E. Knuth in September, 1981; a somewhat similar {\sc SAIL} program had
been developed in March, 1979. Since this program describes itself, a
bootstrapping process involving hand-translation had to be used to get started.
For large \.{WEB} files one should have a large memory, since \.{TANGLE} keeps
all the \PASCAL\ text in memory (in an abbreviated form). The program uses
a few features of the local \PASCAL\ compiler that may need to be changed in
other installations:
\yskip\item{1)} Case statements have a default.
\item{2)} Input-output is done with ascii characters in a way that allows
end-of-page marks to be distinguished from end-of-line marks.
\yskip\noindent
These features are also present in the \PASCAL\ version of \TEX, where they
are used in a similar (but more complex) way. System-dependent portions
of \.{TANGLE} can be identified by looking at the entries for `system
dependencies' in the index below.
@!@↑system dependencies@>
@ The program begins with a fairly normal header, made up of pieces that
@↑system dependencies@>
will mostly be filled in later. The \.{WEB} input comes from file |input|,
the \PASCAL\ output goes to file |output|, the string pool output
goes to file |pool|, and error messages go to the terminal (|tty|).
If it is necessary to abort the job because of a fatal error, the program
calls the `|quit|' procedure, which goes to the label |end←of←TANGLE|.
@d end←of←TANGLE = 9999 {go here to wrap it up}
@p @<Compiler directives@>@/
program TANGLE(@!input,@!output,@!pool,@!tty);
label end←of←TANGLE; {go here to finish}
const @<Constants in the outer block@>@/
type @<Types in the outer block@>@/
var @<Globals in the outer block@>@/
@<Error handling procedures@>@/
procedure initialize;
var @<Local variables for initialization@>@/
begin @<Set initial values@>@/
end;
@ Some of this code is optional for use when debugging only; such material
is enclosed between the delimiters |debug| and $|gubed|$.
Other parts, delimited by |stat| and $|tats|$,
are optionally included if statistics about \.{TANGLE}'s memory
usage are desired. Another small section of the program
@↑system dependencies@>
is used to skip the `directory pages' in files produced with the {\mc E} editor
at Stanford; that code is delimited by |stanford| and $|drofnats|$.
@d debug==@{ {change this to `$\\{debug}\eqv\null$' when debugging}
@d gubed==@} {change this to `$\\{gubed}\eqv\null$' when debugging}
@f debug==begin
@f gubed==end
@#
@d stat==@{ {change this to `$\\{stat}\eqv\null$' when gathering usage statistics}
@d tats==@} {change this to `$\\{tats}\eqv\null$' when gathering usage statistics}
@f stat==begin
@f tats==end
@#
@d stanford==@{ {change this to `$\\{stanford}\eqv\.{@@\{}$' when not
using {\mc E} files}
@d drofnats==@} {change this to `$\\{drofnats}\eqv\.{@@\}}$' when not
using {\mc E} files}
@f stanford==begin
@f drofnats==end
@ The \PASCAL\ compiler used to develop this system has ``compiler
directives'' that can appear in comments whose first character is a dollar sign.
In production versions of \.{TANGLE} these directives tell the compiler that
@↑system dependencies@>
it is safe to avoid range checks and to leave out the extra code it inserts
for the \PASCAL\ debugger's benefit, although interrupts will occur if
there is arithmetic overflow.
@<Compiler directives@>=
@{@&$C-,A+,D-@} {no range check, catch arithmetic overflow, no debug overhead}
debug @{@&$C+,D+@}@+ gubed {but turn everything on when debugging}
@ Labels are given symbolic names by the following definitions. We insert
the label `|exit|:' just before the \&{end} of a procedure in which we have
used the `\&{return}' statement defined below;
the label `|restart|' is occasionally used at the very beginning of a
procedure; and the label `|reswitch|' is occasionally used just prior to
a \&{case} statement in which some cases change the conditions and we wish to
branch to the newly applicable case.
Loops that are set up with the \&{loop} construction defined below are
commonly exited by going to `|done|' or to `|found|' or to `|not←found|',
and they are sometimes repeated by going to `|continue|'.
@d exit=10 {go here to leave a procedure}
@d restart=20 {go here to start a procedure again}
@d reswitch=21 {go here to start a case statement again}
@d continue=22 {go here to resume a loop}
@d done=30 {go here to exit a loop}
@d found=31 {go here when you've found it}
@d not←found=32 {go here when you've found something else}
@ Here are some macros for common programming idioms and for the default
case statement.
@↑system dependencies@>
@d incr(#) == #:=#+1 {increase a variable by unity}
@d decr(#) == #:=#-1 {decrease a variable by unity}
@d loop == @+ while true do@+ {repeat over and over until a |goto| happens}
@d do←nothing == {empty statement}
@d return == goto exit {terminate a procedure call}
@d othercases == others: {default for cases not listed explicitly}
@d endcases == @+ end {follows the default case}
@f othercases == else
@f endcases == end
@f return == nil
@f loop == xclause
@ The following parameters are set big enough to handle \TEX, so they
should be sufficient for most applications of \.{TANGLE}.
@<Constants...@>=
@!buf←size=100; {maximum length of input line}
@!max←bytes=30000; {number of bytes in identifiers, strings, module names;
must be less than 65536}
@!max←toks=65535; {number of bytes in compressed \PASCAL\ code;
must be less than 65536}
@!max←names=4000; {number of identifiers, strings, module names;
must be less than 10240}
@!max←texts=2000; {number of replacement texts, must be less than 10240}
@!hash←size=353; {should be prime}
@!longest←name=300; {module names shouldn't be longer than this}
@!line←length=72; {lines of \PASCAL\ output have at most this many characters}
@!out←buf←size=144; {length of output buffer, should be twice |line←length|}
@!stack←size=50; {number of simultaneous levels of macro expansion}
@!max←id←length=12; {long identifiers are chopped to this length, which must
not exceed |line←length|}
@!unambig←length=7; {identifiers must be unique if chopped to this length}
{note that 7 is more strict than \PASCAL's 8, but this can be varied}
@* The character set.
One of the main goals in the design of \.{WEB} has been to make it readily
portable between a wide variety of computers. Yet \.{WEB} by its
very nature must use a greater variety of characters than most computer
programs deal with, and character encoding is one of the areas in which
existing machines differ most widely from each other.
To resolve this problem, all input to \.{WEAVE} and \.{TANGLE} is converted
to an internal seven-bit code that is essentially standard ascii, the ``American
Standard Code for Information Interchange.'' The conversion is done
immediately when each character is read in. Conversely, characters are
converted from ascii to the user's external representation just before
they are output.
Such an internal code is relevant to users of \.{WEB} only because it is
the code used for preprocessed constants like \.{"A"}. If you are writing
a program in \.{WEB} that makes use of such one-character constants, you
should convert your input to ascii form, like \.{WEAVE} and \.{TANGLE} do.
Otherwise \.{WEB}'s internal coding scheme does not affect you.
@↑ascii code@>
Here is a table of the standard visible ascii codes:
$$\vbox{
\hbox{\hbox to 40pt{\hfill0\hfill}\!
\hbox to 40pt{\hfill1\hfill}\!
\hbox to 40pt{\hfill2\hfill}\!
\hbox to 40pt{\hfill3\hfill}\!
\hbox to 40pt{\hfill4\hfill}\!
\hbox to 40pt{\hfill5\hfill}\!
\hbox to 40pt{\hfill6\hfill}\!
\hbox to 40pt{\hfill7\hfill}}
\vskip 4pt
\hrule
\def\↑{\vrule height 10.5pt depth 4.5pt}
\halign{\hbox to 0pt{\hskip -24pt\O#0\hfill}&\↑
\hbox to 40pt{\:t\hfill#\hfill\↑}&\!
\hbox to 40pt{\:t\hfill#\hfill\↑}&\!
\hbox to 40pt{\:t\hfill#\hfill\↑}&\!
\hbox to 40pt{\:t\hfill#\hfill\↑}&\!
\hbox to 40pt{\:t\hfill#\hfill\↑}&\!
\hbox to 40pt{\:t\hfill#\hfill\↑}&\!
\hbox to 40pt{\:t\hfill#\hfill\↑}&\!
\hbox to 40pt{\:t\hfill#\hfill\↑}\cr
04&\char'40&!&"&\char'43&\char'44&\char'45&\char'46&\char'16\cr
\noalign{\hrule}
05&(&)&*&+&,&-&.&/\cr
\noalign{\hrule}
06&0&1&2&3&4&5&6&7\cr
\noalign{\hrule}
07&8&9&:&;&<&=&>&?\cr
\noalign{\hrule}
10&@@&A&B&C&D&E&F&G\cr
\noalign{\hrule}
11&H&I&J&K&L&M&N&O\cr
\noalign{\hrule}
12&P&Q&R&S&T&U&V&W\cr
\noalign{\hrule}
13&X&Y&Z&[&\char'134&]&\char'17&\char'32\cr
\noalign{\hrule}
14&\char'15&a&b&c&d&e&f&g\cr
\noalign{\hrule}
15&h&i&j&k&l&m&n&o\cr
\noalign{\hrule}
16&p&q&r&s&t&u&v&w\cr
\noalign{\hrule}
17&x&y&z&\char'173&\char'174&\char'175&\char'24\cr}
\hrule width 280pt}$$
(Actually, of course, code @'040 is an invisible blank space.) Code @'136
was once as an upward arrow (\.{\char'136}), and code @'137 was
once a left arrow (\.{\char'137}), in olden times when the first draft
of ascii code was prepared; but \.{WEB} works with today's standard
ascii in which those codes represent a caret and an underline as shown.
@<Types...@>=
@!ascii←code=0..127; {seven-bit numbers, a subrange of the integers}
@ The original \PASCAL\ compiler was designed in the late 60s, when six-bit
character sets were common, so it did not make provision for lower case
letters. Nowadays, of course, we need to deal with both upper and lower case
alphabets in a convenient way, so \.{WEB} assumes that it is being used
with a \PASCAL\ whose character set contains at least the characters of
standard ascii as listed above. Some \PASCAL\ compilers use the original
name |char| for the data type associated with the characters in text files,
while other \PASCAL s consider |char| to be a 64-element subrange of a larger
data type that has some other name.
In order to accommodate this difference, we shall use the name |text←char|
to stand for the data type of the characters on the |input| and |output|
files. We shall also assume that |text←char| consists of the elements
|chr(first←text←char)| through |chr(last←text←char)|, inclusive. The
following definitions should be adjusted if necessary.
@↑system dependencies@>
@d text←char == char {the data type of characters in text files}
@d first←text←char=0 {ordinal number of the smallest element of |text←char|}
@d last←text←char=127 {ordinal number of the largest element of |text←char|}
@<Local variables for init...@>=
i:0..last←text←char;
@ The \.{WEAVE} and \.{TANGLE} processors convert between ascii code and
the user's external character set by means of arrays |xord| and |xchr|
that are analogous to \PASCAL's |ord| and |chr| functions.
@<Globals...@>=
@!xord: array [text←char] of ascii←code; {specifies conversion of input characters}
@!xchr: array [ascii←code] of text←char; {specifies conversion of output characters}
@ If we assume that every system using \.{WEB} is able to read and write the
visible characters of standard ascii (although not necessarily using the
ascii codes to represent them), the following assignment statements initialize
most of the |xchr| array properly, without needing any system-dependent
changes. For example, the statement \.{xchr[@@\'101]:=\'A\'} that appears
in the present \.{WEB} file might be encoded in, say, {\mc EBCDIC} code
on the external medium on which it resides, but \.{TANGLE} will convert from
this external code to ascii and back again. Therefore the assignment
statement \.{XCHR[65]:=\'A\'} will appear in the corresponding \PASCAL\ file,
and \PASCAL\ will compile this statement so that |xchr[65]| receives the
character \.A in the external (|char|) code. Note that it would be quite
incorrect to say \.{xchr[@@\'101]:="A"}, because |"A"| is a constant of
type |integer|, not |char|, and because we have $|"A"|=65$ regardless of
the external character set.
@<Set init...@>=
xchr[@'40]:=' ';
xchr[@'41]:='!';
xchr[@'42]:='"';
xchr[@'43]:='#';
xchr[@'44]:='$';
xchr[@'45]:='%';
xchr[@'46]:='&';
xchr[@'47]:='''';@/
xchr[@'50]:='(';
xchr[@'51]:=')';
xchr[@'52]:='*';
xchr[@'53]:='+';
xchr[@'54]:=',';
xchr[@'55]:='-';
xchr[@'56]:='.';
xchr[@'57]:='/';@/
xchr[@'60]:='0';
xchr[@'61]:='1';
xchr[@'62]:='2';
xchr[@'63]:='3';
xchr[@'64]:='4';
xchr[@'65]:='5';
xchr[@'66]:='6';
xchr[@'67]:='7';@/
xchr[@'70]:='8';
xchr[@'71]:='9';
xchr[@'72]:=':';
xchr[@'73]:=';';
xchr[@'74]:='<';
xchr[@'75]:='=';
xchr[@'76]:='>';
xchr[@'77]:='?';@/
xchr[@'100]:='@@';
xchr[@'101]:='A';
xchr[@'102]:='B';
xchr[@'103]:='C';
xchr[@'104]:='D';
xchr[@'105]:='E';
xchr[@'106]:='F';
xchr[@'107]:='G';@/
xchr[@'110]:='H';
xchr[@'111]:='I';
xchr[@'112]:='J';
xchr[@'113]:='K';
xchr[@'114]:='L';
xchr[@'115]:='M';
xchr[@'116]:='N';
xchr[@'117]:='O';@/
xchr[@'120]:='P';
xchr[@'121]:='Q';
xchr[@'122]:='R';
xchr[@'123]:='S';
xchr[@'124]:='T';
xchr[@'125]:='U';
xchr[@'126]:='V';
xchr[@'127]:='W';@/
xchr[@'130]:='X';
xchr[@'131]:='Y';
xchr[@'132]:='Z';
xchr[@'133]:='[';
xchr[@'134]:='\';
xchr[@'135]:=']';
xchr[@'136]:='↑';
xchr[@'137]:='←';@/
xchr[@'140]:='`';
xchr[@'141]:='a';
xchr[@'142]:='b';
xchr[@'143]:='c';
xchr[@'144]:='d';
xchr[@'145]:='e';
xchr[@'146]:='f';
xchr[@'147]:='g';@/
xchr[@'150]:='h';
xchr[@'151]:='i';
xchr[@'152]:='j';
xchr[@'153]:='k';
xchr[@'154]:='l';
xchr[@'155]:='m';
xchr[@'156]:='n';
xchr[@'157]:='o';@/
xchr[@'160]:='p';
xchr[@'161]:='q';
xchr[@'162]:='r';
xchr[@'163]:='s';
xchr[@'164]:='t';
xchr[@'165]:='u';
xchr[@'166]:='v';
xchr[@'167]:='w';@/
xchr[@'170]:='x';
xchr[@'171]:='y';
xchr[@'172]:='z';
xchr[@'173]:='{';
xchr[@'174]:='|';
xchr[@'175]:='}';
xchr[@'176]:='~';@/
xchr[0]:=' '; xchr[@'177]:=' '; {these ascii codes are not used}
@ Some of the ascii codes below @'40 have been given symbolic names in
\.{WEAVE} and \.{TANGLE} because they are used with a special meaning.
@d down←arrow=@'1 {used for subscripts in many \TEX\ installations}
@d and←sign=@'4 {equivalent to `\.{and}'}
@d not←sign=@'5 {equivalent to `\.{not}'}
@d set←element←sign=@'6 {equivalent to `\.{in}'}
@d tab←mark=@'11 {ascii code used as tab-skip}
@d line←feed=@'12 {ascii code thrown away at end of line}
@d up←arrow=@'13 {used for superscripts in many \TEX\ installations}
@d form←feed=@'14 {ascii code used at end of page}
@d carriage←return=@'15 {ascii code used at end of line}
@d infinity←sign=@'16 {a character that happens to be in font cmtt}
@d circle←times=@'26 {used for alignment tabs in many \TEX\ installations}
@d left←arrow=@'30 {equivalent to `\.{:=}'}
@d right←arrow=@'31 {a character that happens to be in font cmtt}
@d not←equal=@'32 {equivalent to `\.{<>}'}
@d less←or←equal=@'34 {equivalent to `\.{<=}'}
@d greater←or←equal=@'35 {equivalent to `\.{>=}'}
@d equivalence←sign=@'36 {equivalent to `\.{==}'}
@d or←sign=@'37 {equivalent to `\.{or}'}
@ Here now is the system-dependent part of the character set. If \.{WEB} is
being implemented on a garden-variety \PASCAL\ for which only standard ascii
codes will appear in the input and output files, you should simply change
the code in this module to
$$\hbox{|for i:=1 to @'37 do xchr[i]:=' ';|}$$
the more general code here is intended to make \.{WEB} more friendly on
computers that have an extended character set, so that one can type things
like \.\NE\ instead of \.{<>}. People with extended character sets can
assign codes arbitrarily here, giving an |xchr| equivalent to whatever
characters the users of \.{WEB} are allowed to have in their input files,
provided that unsuitable characters do not correspond to special
codes like |down←arrow| and |carriage←return| and |not←equal| that are
listed above.
@↑system dependencies@>
The code shown here is intended to be used on the Stanford {\mc SAIL}
system and at other installations like CMU and USC where essentially the
same extended character set is used. At MIT, the three final assignments
should be eliminated, since \.{WEB}'s character set agrees exactly with
MIT's.
@<Set init...@>=
for i:=1 to @'37 do xchr[i]:=chr(i);
xchr[left←arrow]:=chr(@'137);
xchr[not←equal]:=chr(@'33);
xchr[@'33]:=chr(@'176);
@ The following system-independent code makes the |xord| array contain a
suitable inverse to the information in |xchr|.
@<Set init...@>=
for i:=first←text←char to last←text←char do xord[chr(i)]:=@'40;
for i:=1 to @'176 do xord[xchr[i]]:=i;
@* Input and output.
The input conventions of this program are intended to be very much like those
of \TEX\ (except, of course, that they are much simpler, because much less
needs to be done). Furthermore they are identical to those of \.{WEAVE}.
Therefore people who need to make modifications to all three systems
@↑system dependencies@>
should be able to do so without too many headaches.
However, we use the standard \PASCAL\ input/output procedures here wherever
possible, since \.{TANGLE} does not have to deal with files that are named
dynamically by the user, and since there is no input from the terminal.
@ Terminal output is done by writing on file |tty|, which is assumed to
consist of characters of type |text←char|:
@↑system dependencies@>
@d print(#)==write(tty,#) {`|print|' means write on the terminal}
@d print←ln(#)==write←ln(tty,#) {`|print|' and then start new line}
@d new←line==write←ln(tty) {start new line}
@d print←nl(#)== {print information starting on a new line}
begin new←line; print(#);
end
@ The following code re-opens the |input| file in a mode that allows us
to see end-of-line characters. We would not have to use this procedure
if we did not have several ways to end a line. But the \PASCAL\ used
with an extended ascii character set at Stanford considers that |eoln| occurs
at any of the characters |carriage←return|, |line←feed|, |form←feed|,
|chr(@'32)|, and |chr(@'33)|; these characters would be indistinguishable
from each other if we did not open the file in a special mode.
@↑system dependencies@>
@p procedure open←input; {prepare for ascii input on the |input| file}
begin reset(input,'','/E');
end;
@ String pool constants are written to the |pool| file.
@<Globals...@>=
@!pool: file of text←char;
@ The following code opens |pool|. Since this file was listed in the
program header, the \PASCAL\ runtime system is assumed to have checked
that a suitable file name has been given.
@↑system dependencies@>
@<Set init...@>=
rewrite(pool);
@ Input goes into an array called |buffer|.
@<Globals...@>=@!buffer: array[0..buf←size] of ascii←code;
@ The following procedure gets one line of input, according to the conventions
of \TEX, namely: If the |input| file has been entirely read, |input←ln| returns
|false| and does nothing else. Otherwise if the next item in the file is an
end-of-page mark, the procedure sets |buffer[0]:=form←feed|, |limit:=0|, and
returns |true|. Otherwise |ascii←code| numbers representing the next line
of the file are input into |buffer[0]|, |buffer[1]|, $\ldotss$,
|buffer[limit-1]|; the global variable |limit| is set to the length of the
@↑system dependencies@>
line; |buffer[limit]| is set to an ascii |carriage←return|; and the
procedure returns |true|. It is assumed that none of the |ascii←code| values
of |buffer[j]| for |0<=j<limit| is equal to 0, @'177, |line←feed|, |form←feed|,
or |carriage←return|.
@p function input←ln:boolean; {inputs the next line or returns |false|}
label done;
begin if eof(input) then input←ln:=false
else begin limit:=0; buffer[0]:=xord[input↑];
if buffer[0]=form←feed then read←ln
else loop@+begin if eoln(input)and
(input↑<>chr(@'32))and(input↑<>chr(@'33)) then
begin buffer[limit]:=carriage←return; read←ln;
goto done;
end;
if limit=buf←size-1 then {keep |buffer[buf←size]| empty}
begin buffer[limit]:=carriage←return;
print←nl('! Input line too long'); error; goto done;
@.Input line too long@>
end;
incr(limit); get(input);
if eof(input) then
begin buffer[limit]:=carriage←return; goto done;
end;
buffer[limit]:=xord[input↑];
end;
done: input←ln:=true;
end;
end;
@* Reporting errors to the user.
The \.{TANGLE} processor operates in two phases: first it inputs the source
file and stores a compressed representation of the program, then it produces
the \PASCAL\ output from the compressed representation.
The global variable |phase←one| tells whether we are in Phase I or not.
@<Globals...@>=
@!phase←one: boolean; {|true| in Phase I, |false| in Phase II}
@ If an error is detected while we are debugging,
we usually want to look at the contents of memory.
A special procedure will be declared later for this purpose.
@<Error handling...@>=
debug @+ procedure debug←help; forward;@+ gubed
@ During the first phase, syntax errors are reported to the user by saying
$$\hbox{`|err←print('! Error message')|'},$$
followed by `|quit|' if no recovery from the error is provided.
This will print the error message followed by an indication of where the error
was spotted in the source file. Note that no period follows the error message,
since the error routine will fill this in automatically.
Errors that are noticed during the second phase are reported to the user
in the same fashion, but the error message will be
followed by an indication of where the error was spotted in the output file.
The actual error indications are provided by a procedure called |error|.
@d err←print(#)==begin new←line; print(#); error;
end
@<Error handling...@>=
procedure error; {prints '\..' and location of error message}
var j: 0..out←buf←size; {index into |out←buf|}
@!k,@!l: 0..buf←size; {indices into |buffer|}
begin if phase←one then @<Print error location based on input buffer@>
else @<Print error location based on output buffer@>;
debug debug←help;@+gubed
end;
@ The error locations during Phase I can be indicated by using the global
variables |loc|, |page|, and |line|, which tell respectively the first
unlooked-at position in |buffer|, the current page number, and the current
line number.
@<Print error location based on input buffer@>=
begin print←ln('. (p.', page:0, ',l.', line:0, ')');
if loc>=limit then l:=limit else l:=loc;
for k:=1 to l do
if buffer[k-1]=tab←mark then print(' ')
else print(xchr[buffer[k-1]]); {print the characters already read}
new←line;
for k:=1 to l do print(' '); {space out the next line}
for k:=l+1 to limit do print(xchr[buffer[k-1]]); {print the part not yet read}
print(' '); {this space separates the message from future asterisks}
end
@ The position of errors detected during the second phase can be indicated
by outputting the partially-filled output buffer, which contains |out←ptr|
entries.
@<Print error location based on output...@>=
begin print←ln('. (l.',line:0,')');
for j:=1 to out←ptr do print(xchr[out←buf[j-1]]); {print current partial line}
print('...'); {indicate that this information is partial}
end
@ The |quit| procedure just cuts across all active procedure levels
and jumps out of the program. This is the only non-local |goto| statement
in \.{TANGLE}. It is used when no recovery from a particular error has
been provided.
Some \PASCAL\ compilers do not implement non-local |goto| statements.
@↑system dependencies@>
In such cases the code that appears at label |end←of←TANGLE| should be
copied into the |quit| procedure, followed by a call to a system procedure
that terminates the program.
@d fatal←error(#)==begin new←line; print(#); error; quit;
end
@<Error handling...@>=
procedure quit;
begin goto end←of←TANGLE;
end;
@ Sometimes the program's behavior is far different from what it should be,
and \.{TANGLE} prints an error message that is really for the \.{TANGLE}
maintenance person, not the user. In such cases the program says
|confusion('indication of where we are')|.
@d confusion(#)==fatal←error('! This can''t happen (',#,')')
@.This can't happen@>
@ An overflow stop occurs if \.{TANGLE}'s tables aren't large enough.
@d overflow(#)==fatal←error('! Sorry, ',#,' capacity exceeded')
@.Sorry, x capacity exceeded@>
@* Data structures.
Most of the user's \PASCAL\ code is packed into seven- or eight-bit integers
in two large arrays called |byte←mem| and |tok←mem|.
The |byte←mem| array holds the names of identifiers, strings, and modules;
the |tok←mem| array holds the replacement texts
for macros and modules. Allocation is sequential, since things are deleted only
during Phase II, and only in a last-in-first-out manner.
Auxiliary arrays |byte←start| and |tok←start| are used as directories to
|byte←mem| and |tok←mem|, and the |link|, |ilk|, |equiv|, and |text←link|
arrays give further information about names. These auxiliary arrays
consist of sixteen-bit items.
@<Types...@>=
@!eight←bits=0..255; {unsigned one-byte quantity}
@!sixteen←bits=0..65535; {unsigned two-byte quantity}
@ @<Globals...@>=
@!byte←mem: packed array [0..max←bytes] of ascii←code; {characters of names}
@!tok←mem: packed array [0..max←toks] of eight←bits; {tokens}
@!byte←start: array [0..max←names] of sixteen←bits; {directory into |byte←mem|}
@!tok←start: array [0..max←texts] of sixteen←bits; {directory into |tok←mem|}
@!link: array [0..max←names] of sixteen←bits; {hash table or tree links}
@!ilk: array [0..max←names] of sixteen←bits; {type codes or tree links}
@!equiv: array [0..max←names] of sixteen←bits; {info corresponding to names}
@!text←link: array [0..max←texts] of sixteen←bits; {relates replacement texts}
@ The names of identifiers are found by computing a hash address |h| and
then looking at strings of bytes signified by |hash[h]|, |link[hash[h]]|,
|link[link[hash[h]]]|, $\ldotss$, until either finding the desired name
or encountering a zero.
A `|name←pointer|' variable, which signifies a name, is an index into
|byte←start|. The actual sequence of characters in the name pointed to by
$p$ appears in positions |byte←start[p]| to |byte←start[p+1]-1|, inclusive,
in |byte←mem|. The pointer 0 is used for undefined module names; we don't
want to use it for the names of identifiers, since 0 stands for a null
pointer in a linked list.
Strings are treated like identifiers; the first character (a double-quote)
distinguishes a string from an alphabetic name, but for \.{TANGLE}'s purposes
strings behave like numeric macros. (A `string' here refers to the
strings delimited by double-quotes that \.{TANGLE} processes. \PASCAL\
string constants delimited by single-quote marks are not given such special
treatment, they simply appear as sequences of characters in the \PASCAL\
texts.) The total number of strings in the string
pool is called |string←ptr|; the total number of names in |byte←mem|
is called |name←ptr|; and the total number of bytes occupied in
|byte←mem| is called |byte←ptr|.
We usually have |byte←start[name←ptr]=byte←ptr|, since this identifies the
end of the most recently created name, which is pointed to by |(name←ptr-1)|.
@d length(#)==byte←start[#+1]-byte←start[#] {the length of a name}
@<Types...@>=
@!name←pointer=0..max←names; {identifies a name}
@ @<Global...@>=
@!name←ptr:name←pointer; {first unused position in |byte←start|}
@!string←ptr:name←pointer; {next number to be given to a string of length |<>1|}
@!byte←ptr:0..max←bytes; {first unused position in |byte←mem|}
@ @<Set init...@>=
name←ptr:=1; string←ptr:=128; byte←ptr:=1; byte←start[0]:=1; byte←start[1]:=1;
@ Replacement texts are stored in |tok←mem|, using similar conventions.
A `|text←pointer|' variable is an index into |tok←start|, and the replacement
text that corresponds to $p$
runs from positions |tok←start[p]| to |tok←start[p+1]-1|, inclusive.
Furthermore, |text←link[p]| is used to connect pieces of text that
have the same name, as we shall see later. The pointer 0 is used
for undefined replacement texts.
The first position of |tok←mem|
that is unoccupied by replacement text is called |tok←ptr|, and the first
unused location of |tok←start| is called |text←ptr|.
We usually have |tok←start[text←ptr]=tok←ptr|, for the same reason that
|byte←start[name←ptr]| is usually equal to |byte←ptr|.
@<Types...@>=
@!text←pointer=0..max←texts; {identifies a replacement text}
@ @<Glob...@>=
@t\hskip1em@>@!text←ptr:text←pointer; {first unused position in |tok←start|}
@t\hskip1em@>@!tok←ptr:0..max←toks; {first unused position in |tok←mem|}
stat @!max←tok←ptr:0..max←toks; {largest value assumed by |tok←ptr|}
tats
@ @<Set init...@>=
tok←ptr:=1; text←ptr:=1; tok←start[0]:=1; tok←start[1]:=1;
@ Four types of identifiers are distinguished by their |ilk|:
\yskip\hang |normal| identifiers will appear in the \PASCAL\ program as
ordinary identifiers since they have not been defined to be macros; the
corresponding value in the |equiv| array
for such identifiers is a link in a secondary hash table that
is used to check whether any two of them agree in their first |unambig←length|
characters after underline symbols are removed and lower case letters are
changed to upper case.
\yskip\hang |numeric| identifiers have been defined to be numeric macros;
their |equiv| value contains the corresponding numeric value plus $2↑{15}$.
Strings are treated as numeric macros.
\yskip\hang |simple| identifiers have been defined to be simple macros;
their |equiv| value points to the corresponding replacement text.
\yskip\hang |parametric| identifiers have been defined to be parametric macros;
like simple identifiers, their |equiv| value points to the replacement text.
@d normal=0 {ordinary identifiers have |normal| ilk}
@d numeric=1 {numeric macros and strings have |numeric| ilk}
@d simple=2 {simple macros have |simple| ilk}
@d parametric=3 {parametric macros have |parametric| ilk}
@ The names of modules are stored in |byte←mem| together
with the identifier names, but a hash table is not used for them because
\.{TANGLE} needs to be able to recognize a module name when given a prefix of
that name. A conventional binary seach tree is used to retrieve module names,
with fields called |llink| and |rlink| in place of |link| and |ilk|. The
root of this tree is |rlink[0]|. If $p$ is a pointer to a module name,
|equiv[p]| points to its replacement text, just as in simple and parametric
macros, unless this replacement text has not yet been defined (in which case
|equiv[p]=0|).
@d llink==link {left link in binary search tree for module names}
@d rlink==ilk {right link in binary search tree for module names}
@<Set init...@>=
rlink[0]:=0; {the binary search tree starts out with nothing in it}
equiv[0]:=0; {the undefined module has no replacement text}
@ Here is a little procedure that prints the text of a given name.
@p procedure print←id(@!p:name←pointer); {print identifier or module name}
var k:0..max←bytes; {index into |byte←mem|}
begin if p>=name←ptr then print('IMPOSSIBLE')
else for k:=byte←start[p] to byte←start[p+1]-1 do print(xchr[byte←mem[k]]);
end;
@* Searching for identifiers.
The hash table described above is updated by the |id←lookup| procedure,
which finds a given identifier and returns a pointer to its index in
|byte←start|. If the identifier was not already present, it is inserted with
a given |ilk| code; and an error message is printed if the identifier is being
doubly defined.
Because of the way \.{TANGLE}'s scanning mechanism works, it is most convenient
to let |id←lookup| search for an identifier that is present in the |buffer|
array. Two other global variables specify its position in the buffer: the
first character is |buffer[id←first]|, and the last is |buffer[id←loc-1]|.
Furthermore, if the identifier is really a string, the global variable
|double←chars| tells how many of the characters in the buffer appear
twice (namely \.{@@@@} and \.{""}), since this additional information makes
it easy to calculate the true length of the string. The final double-quote
of the string is not included in its ``identifier,'' but the first one is,
so the string length is |id←loc-id←first-double←chars-1|.
We have mentioned that |normal| identifiers belong to two hash tables,
one for their true names as they appear in the \.{WEB} file and the other
when they have been reduced to their first |unambig←length| characters.
The hash tables are kept by the method of simple chaining, where the
heads of the individual lists appear in the |hash| and |chop←hash| arrays.
If |h| is a hash code, the primary hash table list starts at |hash[h]| and
proceeds through |link| pointers; the secondary hash table list starts at
|chop←hash[h]| and proceeds through |equiv| pointers. Of course, the same
identifier will probably have two different values of |h|.
The |id←lookup| procedure uses an auxiliary array called |chopped←id| to
contain up to |unambig←length| characters of the current identifier, if
it is necessary to compute the secondary hash code. (This array could be
declared local to |id←lookup|, but in general we are making all array
declarations global in this program, because some compilers and some machine
architectures make dynamic array allocation inefficient.)
@<Glob...@>=
@!id←first:0..buf←size; {where the current identifier begins in the buffer}
@!id←loc:0..buf←size; {just after the current identifier in the buffer}
@!double←chars:0..buf←size; {correction to length in case of strings}
@#
@!hash,@!chop←hash:array [0..hash←size] of sixteen←bits; {heads of hash lists}
@!chopped←id:array [0..unambig←length] of ascii←code; {chopped identifier}
@ Initially all the hash lists are empty.
@<Local variables for init...@>=
@!h:0..hash←size; {index into hash-head arrays}
@ @<Set init...@>=
for h:=0 to hash←size-1 do
begin hash[h]:=0; chop←hash[h]:=0;
end;
@ Here now is the main procedure for finding identifiers (and strings).
The parameter $t$ is set to |normal| except when the identifier is
a macro name that is just being defined; in the latter case, $t$ will be
|numeric|, |simple|, or |parametric|.
@p function id←lookup(@!t:eight←bits):name←pointer; {finds current identifier}
label found, not←found;
var c:eight←bits; {byte being chopped}
@!i:0..buf←size; {index into |buffer|}
@!h:0..hash←size; {hash code}
@!k:0..max←bytes; {index into |byte←mem|}
@!l:0..buf←size; {length of the given identifier}
@!p,@!q:name←pointer; {where the identifier is being sought}
@!s:0..unambig←length; {index into |chopped←id|}
begin l:=id←loc-id←first; {compute the length}
@<Compute the hash code $h$@>;
@<Compute the name location $p$@>;
if (p=name←ptr)or(t<>normal) then
@<Update the tables and check for possible errors@>;
id←lookup:=p;
end;
@ A simple hash code is used: If the sequence of
ascii codes is $c←1c←2\ldotsm c←m$, its hash value will be
$$(2↑{n-1}c←1+2↑{n-2}c←2+\cdots+c←n)\modop|hash←size|.$$
@<Compute the hash...@>=
h:=buffer[id←first]; i:=id←first+1;
while i<id←loc do
begin h:=(h+h+buffer[i]) mod hash←size; incr(i);
end
@ If the identifier is new, it will be placed in position |p=name←ptr|,
otherwise $p$ will point to its existing location.
@<Compute the name location...@>=
p:=hash[h];
while p<>0 do
begin if length(p)=l then
@<Compare name $p$ with current identifier, |goto found| if equal@>;
p:=link[p];
end;
p:=name←ptr; {the current identifier is new}
link[p]:=hash[h]; hash[h]:=p; {insert $p$ at beginning of hash list}
found:
@ @<Compare name $p$...@>=
begin i:=id←first; k:=byte←start[p];
while (i<id←loc)and(buffer[i]=byte←mem[k]) do
begin incr(i); incr(k);
end;
if i=id←loc then goto found; {all characters agree}
end
@ @<Update the tables...@>=
begin if ((p<>name←ptr)and(t<>normal)and(ilk[p]=normal)) or
((p=name←ptr)and(t=normal)and(buffer[id←first]<>"""")) then
@<Compute the secondary hash code $h$ and put the first characters
into the auxiliary array |chopped←id|@>;
if p<>name←ptr then @<Give double-definition error and change $p$ to type $t$@>
else @<Enter a new identifier into the table at position $p$@>;
end
@ The following routine, which is called into play when it is necessary to
look at the secondary hash table, computes the same hash function as before
(but on the chopped data), and places a zero after the chopped identifier
in |chopped←id| to serve as a convenient sentinel.
@<Compute the secondary...@>=
begin i:=id←first; s:=0; h:=0;
while (i<id←loc)and(s<unambig←length) do
begin if buffer[i]<>"←" then
begin if buffer[i]>="a" then chopped←id[s]:=buffer[i]-@'40
else chopped←id[s]:=buffer[i];
h:=(h+h+chopped←id[s]) mod hash←size; incr(s);
end;
incr(i);
end;
chopped←id[s]:=0;
end
@ If a macro has appeared before it was defined, \.{TANGLE} will
still work all right; after all, such behavior is typical of the replacement
texts for modules, which act very much like macros. However, an undefined
numeric macro
may not be used on the right-hand side of another numeric macro definition,
so \.{TANGLE} finds it simplest to make a blanket rule that macros should
be defined before they are used. The following routine gives an error message
and also fixes up any damage that may have been caused.
@<Give double...@>= {now |p<>name←ptr| and |t<>normal|}
begin if ilk[p]=normal then
begin err←print('! This identifier has already appeared');
@.This identifier has already...@>
@<Remove $p$ from secondary hash table@>;
end
else err←print('! This identifier was defined before');
@.This identifier was defined...@>
ilk[p]:=t;
end
@ When we have to remove a secondary hash entry, because a |normal| identifier
is changing to another |ilk|, the hash code $h$ and chopped identifier have
already been computed.
@<Remove $p$ from secondary...@>=
q:=chop←hash[h];
if q=p then chop←hash[h]:=equiv[p]
else begin while equiv[q]<>p do q:=equiv[q];
equiv[q]:=equiv[p];
end
@ The following routine could make good use of a generalized |pack| procedure
that puts items into just part of a packed array instead of the whole thing.
@<Enter a new identifier...@>=
begin if (t=normal)and(buffer[id←first]<>"""") then
@<Check for ambiguity and update secondary hash@>;
if byte←ptr+l>max←bytes then overflow('byte memory');
if name←ptr=max←names then overflow('name');
i:=id←first; k:=byte←ptr; {get ready to move the identifier into |byte←mem|}
while i<id←loc do
begin byte←mem[k]:=buffer[i]; incr(k); incr(i);
end;
byte←ptr:=k; incr(name←ptr); byte←start[name←ptr]:=k;
if buffer[id←first]<>"""" then ilk[p]:=t
else @<Define and output a new string of the pool@>;
end
@ @<Check for ambig...@>=
begin q:=chop←hash[h];
while q<>0 do
begin @<Check if $q$ conflicts with $p$@>;
q:=equiv[q];
end;
equiv[p]:=chop←hash[h]; chop←hash[h]:=p; {put $p$ at front of secondary list}
end
@ @<Check if $q$ conflicts...@>=
begin k:=byte←start[q]; s:=0;
while (k<byte←start[q+1]) and (s<unambig←length) do
begin c:=byte←mem[k];
if c<>"←" then
begin if c>="a" then c:=c-@'40; {convert to upper case}
if chopped←id[s]<>c then goto not←found;
incr(s);
end;
incr(k);
end;
if (k=byte←start[q+1])and(chopped←id[s]<>0) then goto not←found;
print←nl('! Identifier conflict with ');
@.Identifier conflict...@>
for k:=byte←start[q] to byte←start[q+1]-1 do print(xchr[byte←mem[k]]);
error; q:=0; {only one conflict will be printed, since |equiv[0]=0|}
not←found:
end
@ @↑preprocessed strings@>
@<Define and output a new string...@>=
begin ilk[p]:=numeric; {strings are like numeric macros}
if l-double←chars=2 then {this string is for a single character}
equiv[p]:=buffer[id←first+1]+@'100000
else begin equiv[p]:=string←ptr+@'100000;
l:=l-double←chars-1;
if l>99 then err←print('! Preprocessed string is too long');
@.Preprocessed string is too long@>
incr(string←ptr);
write(pool,xchr["0"+l div 10],xchr["0"+l mod 10]); {output the length}
i:=id←first+1;
while i<id←loc do
begin write(pool,xchr[buffer[i]]); {output characters of string}
if (buffer[i]="""") or (buffer[i]="@@") then
i:=i+2 {omit second appearance of doubled character}
else incr(i);
end;
end;
end
@* Searching for module names.
The |mod←lookup| procedure finds the module name |module[1..l]| in the
search tree, after inserting it if necessary, and returns a pointer to
where it was found.
@<Glob...@>=
@!module:array [0..longest←name] of ascii←code; {name being sought for}
@ According to the rules of \.{WEB}, no module name
should be a proper prefix of another, so a ``clean'' comparison should
occur between any two names. The result of |mod←lookup| is 0 if this
prefix condition is violated. An error message is printed when such violations
are detected during phase two of \.{WEAVE}.
@p function mod←lookup(@!l:sixteen←bits):name←pointer; {finds module name}
label found;
var c:(@!less,@!equal,@!greater,@!prefix,@!extension);
{comparison between two names}
@!j:0..longest←name; {index into |module|}
@!k:0..max←bytes; {index into |byte←mem|}
@!p:name←pointer; {current node of the search tree}
@!q:name←pointer; {father of node $p$}
begin c:=greater; q:=0; p:=rlink[0]; {|rlink[0]| is the root of the tree}
while p<>0 do
begin @<Set \(|c| to the result of comparing the given name to
name $p$@>;
q:=p;
if c=less then p:=llink[q]
else if c=greater then p:=rlink[q]
else goto found;
end;
@<Enter a new module name into the tree@>;
found: if c<>equal then
begin err←print('! Incompatible module names'); p:=0;
@.Incompatible module names@>
end;
mod←lookup:=p;
end;
@ @<Enter a new module name...@>=
if byte←ptr+l>max←bytes then overflow('byte memory');
if name←ptr=max←names then overflow('name');
p:=name←ptr;
if c=less then llink[q]:=p else rlink[q]:=p;
llink[p]:=0; rlink[p]:=0; c:=equal; equiv[p]:=0;
for j:=1 to l do byte←mem[byte←ptr+j-1]:=module[j];
byte←ptr:=byte←ptr+l; incr(name←ptr); byte←start[name←ptr]:=byte←ptr;
@ @<Set \(|c|...@>=
begin k:=byte←start[p]; c:=equal; j:=1;
while (k<byte←start[p+1]) and (j<=l) and (module[j]=byte←mem[k]) do
begin incr(k); incr(j);
end;
if k=byte←start[p+1] then
if j>l then c:=equal
else c:=extension
else if j>l then c:=prefix
else if module[j]<byte←mem[k] then c:=less
else c:=greater;
end
@ The |prefix←lookup| procedure is supposed to find exactly one module
name that has |module[1..l]| as a prefix. Actually the algorithm silently
accepts also the situation that some module name is a prefix of |module[1..l]|,
because the user who painstakingly typed in more than necessary probably
doesn't want to be told about the wasted effort.
@p function prefix←lookup(@!l:sixteen←bits):name←pointer; {finds name extension}
label found;
var c:(less,equal,greater,prefix,extension); {comparison between two names}
@!count:0..max←names; {the number of hits}
@!j:0..longest←name; {index into |module|}
@!k:0..max←bytes; {index into |byte←mem|}
@!p:name←pointer; {current node of the search tree}
@!q:name←pointer; {another place to resume the search after one branch is done}
@!r:name←pointer; {extension found}
begin q:=0; p:=rlink[0]; count:=0; r:=0; {begin search at root of tree}
while p<>0 do
begin @<Set \(|c|...@>;
if c=less then p:=llink[p]
else if c=greater then p:=rlink[p]
else begin r:=p; incr(count); q:=rlink[p]; p:=llink[p];
end;
if p=0 then
begin p:=q; q:=0;
end;
end;
if count<>1 then
if count=0 then err←print('! Name does not match')
@.Name does not match@>
else err←print('! Ambiguous prefix');
@.Ambiguous prefix@>
prefix←lookup:=r; {the result will be 0 if there was no match}
end;
@* Tokens.
Replacement texts, which represent \PASCAL\ code in a compressed format,
appear in |tok←mem| as mentioned above. The codes in
these texts are called `tokens'; some tokens occupy two consecutive
eight-bit byte positions, and the others take just one byte.
If $p>0$ points to a replacement text, |tok←start[p]| is the |tok←mem| position
of the first eight-bit code of that text. If |text←link[p]=0|,
this is the replacement text for a macro, otherwise it is the replacement
text for a module. In the latter case |text←link[p]| is either equal to
|module←flag|, which means that there is no further text for this module, or
|text←link[p]| points to a
continuation of this replacement text; such links are created when
several modules have \PASCAL\ texts with the same name, and they also
tie together all the \PASCAL\ texts of unnamed modules.
The replacement text pointer for the first unnamed module
appears in |text←link[0]|, and the most recent such pointer is |last←unnamed|.
@d module←flag==max←texts {final |link| in module replacement texts}
@<Glob...@>=
@!last←unnamed:text←pointer; {most recent replacement text of unnamed module}
@ @<Set init...@>= last←unnamed:=0; text←link[0]:=0;
@ If the first byte of a token is less than @'200, the token occupies a
single byte. Otherwise we make a sixteen-bit token by combining two consecutive
bytes $a$ and $b$. If |@'200<=a<@'250|, then $(a-@'200)\times2↑8+b$ points
to an identifier; if |@'250<=a<@'320|, then
$(a-@'250)\times2↑8+b$ points to a module name; otherwise, i.e., if
|@'320<=a<@'400|, then $(a-@'320)\times2↑8+b$ is the number of the module
in which the current replacement text appears.
Codes less than @'200 are 7-bit ascii codes that represent themselves.
In particular, a single-character identifier like `|x|' will be a one-byte
token, while all longer identifiers will occupy two bytes.
Some of the 7-bit ascii codes will not be present, however, so we can
use them for special purposes. The following symbolic names are used:
\yskip\hang |begin←comment| denotes \.{@@\{}, which will become either
\.{\{} or \.{[}.
\yskip\hang |end←comment| denotes \.{@@\}}, which will become either
\.{\}} or \.{]}.
\yskip\hang |octal| denotes the \.{@@'} that precedes an octal constant.
\yskip\hang |param| denotes insertion of a parameter. This occurs only in
the replacement texts of parametric macros, outside of single-quoted strings
in those texts.
\yskip\hang |join| denotes the concatenation of adjacent items with no
space or line breaks allowed between them (the \.{@@\&} operation of \.{WEB}).
\yskip\hang |double←dot| denotes `\.{..}' in \PASCAL.
@↑ascii code@>
@d begin←comment=@'11 {ascii tab mark will not appear}
@d end←comment=@'12 {ascii line feed will not appear}
@d octal=@'14 {ascii form feed will not appear}
@d param=@'15 {ascii carriage return will not appear}
@d double←dot=@'40 {ascii space will not appear except in strings}
@d join=@'177 {ascii delete will not appear}
@ The following procedure is used to enter a two-byte value into
|tok←mem| when a replacement text is being generated.
@p procedure store←two←bytes(@!x:sixteen←bits); {stores high byte, then low byte}
begin if tok←ptr+2>max←toks then overflow('token');
tok←mem[tok←ptr]:=x div@'400; {this could be done by a shift command}
tok←mem[tok←ptr+1]:=x mod@'400; {this could be done by a logical and}
tok←ptr:=tok←ptr+2;
end;
@ When \.{TANGLE} is being operated in debug mode, it has a procedure to display
a replacement text in symbolic form. This procedure has not been spruced up to
generate a real great format, but at least the results are not as bad as
a memory dump.
@p debug procedure print←repl(@!p:text←pointer);
var k:0..max←toks; {index into |tok←mem|}
@!a: sixteen←bits; {current byte(s)}
begin if p>=text←ptr then print('BAD')
else begin k:=tok←start[p];
while k<tok←start[p+1] do
begin a:=tok←mem[k];
if a>=@'200 then @<Display two-byte token starting with $a$@>
else @<Display one-byte token $a$@>;
incr(k);
end;
end;
end;
gubed
@ @<Display two-byte...@>=
begin incr(k);
if a<@'250 then {identifier or string}
begin a:=(a-@'200)*@'400+tok←mem[k]; print←id(a);
if byte←mem[byte←start[a]]="""" then print('"')
else print(' ');
end
else if a<@'320 then {module name}
begin print('@@<'); print←id((a-@'250)*@'400+tok←mem[k]);
print('@@>');
end
else begin a:=(a-@'320)*@'400+tok←mem[k]; {module number}
print('@@{',a:0,'@@',xchr["}"]); {can't use right brace
between \&{debug} and \&{gubed}}
end;
end
@ @<Display one-byte...@>=
case a of
begin←comment: print('@@{');
end←comment: print('@@',xchr["}"]); {can't use right brace
between \&{debug} and \&{gubed}}
octal: print('@@''');
param: print('#');
"@@": print('@@@@');
othercases print(xchr[a])
endcases
@* Stacks for output.
Let's make sure that our data structures contain enough information to
produce the entire \PASCAL\ program as desired, by working next on the
algorithms that actually do produce that program.
@ The output process uses a stack to keep track of what is going on at
different ``levels'' as the macros are being expanded.
Entries on this stack have four parts:
\yskip\hang |end←field| is the |tok←mem| location where the replacement
text of a particular level will end;
\hang |byte←field| is the |tok←mem| location from which the next token
on a particular level will be read;
\hang |name←field| points to the name corresponding to a particular level;
\hang |repl←field| points to the replacement text currently being read
at a particular level. (The |name←field| is not sufficient by itself, because
replacement texts can be chained together in their |text←link| fields.)
\yskip\noindent The current values of these four quantities are referred to
quite frequently, so they are stored in a separate place instead of in
the |stack| array. We call the current values |cur←end|, |cur←byte|,
|cur←name|, and |cur←repl|.
The global variable |stack←ptr| tells how many levels of output are
currently in progress. The end of all output occurs when the stack is
empty, i.e., when |stack←ptr=0|.
@<Types...@>=
@t\4@>@!output←state=record
@!end←field: sixteen←bits; {ending location of replacement text}
@!byte←field: sixteen←bits; {present location within replacement text}
@!name←field: name←pointer; {|byte←start| index for text being output}
@!repl←field: text←pointer; {|tok←start| index for text being output}
end;
@ @d cur←end==cur←state.end←field {current ending location in |tok←mem|}
@d cur←byte==cur←state.byte←field {location of next output byte in |tok←mem|}
@d cur←name==cur←state.name←field {pointer to current name being expanded}
@d cur←repl==cur←state.repl←field {pointer to current replacement text}
@<Globals...@>=
@!cur←state : output←state; {|cur←end|, |cur←byte|, |cur←name|, |cur←repl|}
@!stack : array [1..stack←size] of output←state; {info for non-current levels}
@!stack←ptr: 0..stack←size; {first unused location in the output state stack}
@ Parameters must also be stacked. They are placed in
|tok←mem| just above the other replacement texts, and dummy parameter
`names' are placed in |byte←start| just after the other names.
The variables |text←ptr| and |tok←ptr| essentially serve as parameter
stack pointers during the output phase, so there is no need for a separate
data structure to handle this problem.
@ There is an implicit stack corresponding to meta-comments that are output
via \.{@@\{} and \.{@@\}}. But this stack need not be represented in detail,
because we only need to know whether it is empty or not. A global variable
|brace←level| tells how many items would be on this stack if it were present.
@<Globals...@>=
@!brace←level: eight←bits; {current depth of $\.{@@\{}\ldotsm\.{@@\}}$ nesting}
@ To get the output process started, we will perform the following
initialization steps. We may assume that |text←link[0]| is nonzero, since it
points to the \PASCAL\ text in the first unnamed module that generates
code; if there are no such modules, there is nothing to output, and an
error message will have been generated before we do any of the initialization.
@<Initialize the output stacks@>=
stack←ptr:=1; brace←level:=0; cur←name:=0; cur←repl:=text←link[0];
cur←byte:=tok←start[cur←repl]; cur←end:=tok←start[cur←repl+1];
@ When the replacement text for name $p$ is to be inserted into the output,
the following subroutine is called to save the old level of output and get
the new one going.
@p procedure push←level(@!p:name←pointer); {suspends the current level}
begin if stack←ptr=stack←size then overflow('stack')
else begin stack[stack←ptr]:=cur←state; {save |cur←end|, |cur←byte|, etc.}
incr(stack←ptr);
cur←name:=p; cur←repl:=equiv[p]; cur←byte:=tok←start[cur←repl];
cur←end:=tok←start[cur←repl+1];
end;
end;
@ When we come to the end of a replacement text, the |pop←level| subroutine
does the right thing: It either moves to the continuation of this replacement
text or returns the state to the most recently stacked level. Part of this
subroutine, which updates the parameter stack, will be given later when we
study the parameter stack in more detail.
@p procedure pop←level; {do this when |cur←byte| reaches |cur←end|}
label exit;
begin if text←link[cur←repl]=0 then {end of macro expansion}
begin if ilk[cur←name]=parametric then
@<Remove a parameter from the parameter stack@>;
end
else if text←link[cur←repl]<module←flag then {link to a continuation}
begin cur←repl:=text←link[cur←repl]; {we will stay on the same level}
cur←byte:=tok←start[cur←repl]; cur←end:=tok←start[cur←repl+1];
return;
end;
decr(stack←ptr); {we will go down to the previous level}
if stack←ptr>0 then cur←state:=stack[stack←ptr];
exit: end;
@ The heart of the output procedure is the |get←output| routine, which produces
the next token of output that is not a reference to a macro. This procedure
handles all the stacking and unstacking that is necessary. It returns the
value |number| if the next output has a numeric value (the value of a
numeric macro or string), in which case |cur←val| has been set to the
number in question. The procedure also returns the value |new←module| if the
next output begins the replacement text of some module, in which case
|cur←val| is that module's number. And it returns the value |identifier| if
the next output is an identifier of length two or more, in which case
|cur←val| points to that identifier name.
@d number=@'200 {code returned by |get←output| when next output is numeric}
@d module←number=@'201 {code returned by |get←output| for module numbers}
@d identifier=@'202 {code returned by |get←output| for identifiers}
@<Globals...@>=
@!cur←val:integer; {additional information corresponding to output token}
@ If |get←output| finds that no more output remains, it returns the value zero.
@p function get←output:sixteen←bits; {returns next token after macro expansion}
label restart, done;
var a:sixteen←bits; {value of current byte}
@!b:eight←bits; {byte being copied}
@!bal:sixteen←bits; {excess of \.( versus \.) while copying a parameter}
begin restart: if stack←ptr=0 then a:=0
else begin if cur←byte=cur←end then
begin pop←level; goto restart;
end;
a:=tok←mem[cur←byte]; incr(cur←byte);
if a<@'200 then {one-byte token}
begin if a=param then
@<Start scanning current macro parameter, |goto restart|@>;
end
else begin a:=(a-@'200)*@'400+tok←mem[cur←byte]; incr(cur←byte);
if a<@'24000 then {|@'24000=(@'250-@'200)*@'400|}
@<Expand macro $a$, |goto restart| if no output found@>
else if a<@'50000 then {|@'50000=(@'320-@'200)*@'400|}
@<Expand module |a-@'24000|, |goto restart|@>
else begin cur←val:=a-@'50000; a:=module←number;
end;
end;
end;
debug if trouble←shooting then debug←help;@;@+gubed@/
get←output:=a;
end;
@ The user may have forgotten to give any \PASCAL\ text for a module name,
or the \PASCAL\ text may have been associated with a different name by mistake.
@<Expand module |a-...@>=
begin a:=a-@'24000;
if equiv[a]<>0 then push←level(a)
else if a<>0 then
begin print←nl('! Not present: <'); print←id(a); print('>'); error;
@.Not present: <module name>@>
end;
goto restart;
end
@ @<Expand macro ...@>=
begin case ilk[a] of
normal: begin cur←val:=a; a:=identifier;
end;
numeric: begin cur←val:=equiv[a]-@'100000; a:=number;
end;
simple: begin push←level(a); goto restart;
end;
parametric: begin @<Put a parameter on the parameter stack,
or |goto restart| if error occurs@>;
push←level(a); goto restart;
end;
othercases confusion('output')
endcases
end
@ We come now to the interesting part, the job of putting a parameter on
the parameter stack. First we pop the stack if necessary until getting to
a level that hasn't ended. Then the next character must be a `\.(';
and since parentheses are balanced on each level, the entire parameter must
be present, so we can copy it without difficulty.
@<Put a parameter...@>=
while (cur←byte=cur←end)and(stack←ptr>0) do pop←level;
if (stack←ptr=0)or(tok←mem[cur←byte]<>"(") then
begin print←nl('! No parameter given for '); print←id(a); error;
@.No parameter given for macro@>
goto restart;
end;
@<Copy the parameter into |tok←mem|@>;
equiv[name←ptr]:=text←ptr; ilk[name←ptr]:=simple;
debug if byte←ptr=max←bytes then overflow('byte memory');
byte←mem[byte←ptr]:="#"; incr(byte←ptr);
gubed {this code has set the parameter identifier for debugging printouts}
if name←ptr=max←names then overflow('name');
incr(name←ptr); byte←start[name←ptr]:=byte←ptr;
if text←ptr=max←texts then overflow('text');
text←link[text←ptr]:=0; incr(text←ptr); tok←start[text←ptr]:=tok←ptr;
@ The |pop←level| routine undoes the effect of parameter-pushing when
a parameter macro is finished:
@<Remove a parameter...@>=
begin
stat if tok←ptr>max←tok←ptr then max←tok←ptr:=tok←ptr;
tats {the maximum value of |tok←ptr| occurs just before parameter popping}
decr(name←ptr); decr(text←ptr); tok←ptr:=tok←start[text←ptr];
debug decr(byte←ptr);@+gubed
end
@ When a parameter occurs in a replacement text, we treat it as a simple
macro in position (|name←ptr-1|):
@<Start scanning...@>=
begin push←level(name←ptr-1); goto restart;
end
@ Similarly, a |param| token encountered as we copy a parameter is converted
into a simple macro call for |name←ptr-1|.
Some care is needed to handle cases like |macro(#; print('#)'))|; the \.{\#}
token will have been changed to |param| outside of strings, but we still
must distinguish `real' parentheses from those in strings.
@d app←repl(#)==begin if tok←ptr=max←toks then overflow('token');
tok←mem[tok←ptr]:=#; incr(tok←ptr); end
@<Copy the parameter...@>=
bal:=1; incr(cur←byte); {skip the opening `\.('}
loop@+ begin b:=tok←mem[cur←byte]; incr(cur←byte);
if b=param then store←two←bytes(name←ptr+@'77777)
else begin if b>=@'200 then
begin app←repl(b);
b:=tok←mem[cur←byte]; incr(cur←byte);
end
else case b of
"(": incr(bal);
")": begin decr(bal);
if bal=0 then goto done;
end;
"'": repeat app←repl(b);
b:=tok←mem[cur←byte]; incr(cur←byte);
until b="'"; {copy string, don't change |bal|}
othercases do←nothing
endcases;
app←repl(b);
end;
end;
done:
@* Producing the output.
The |get←output| routine above handles most of the complexity of output
generation, but there are two further considerations that have a nontrivial
effect on \.{TANGLE}'s algorithms.
First, we want to make sure that the output is broken into lines not
exceeding |line←length| characters per line, where these breaks occur at
valid places (e.g., not in the middle of a string or a constant or an
identifier, not between `\.<' and `\.>', not at a `\.{@@\&}' position
where quantities are being joined together. Therefore we assemble the
output into a buffer before deciding where the line breaks will appear.
However, we make very little attempt to make ``logical'' line breaks that
would enhance the readability of the output; people are supposed to read
the input of \.{TANGLE} or the \TEX ed output of \.{WEAVE}, but not the
tangled-up output. The only concession to readability is that a break after
a semicolon will be made if possible, since commonly used ``pretty
printing'' routines give better results in such cases.
Second, we want to decimalize octal constants, and to combine integer
quantities that are added or subtracted, because \PASCAL\ doesn't allow
constant expressions in subrange types or in case labels. This means we
want to have a procedure that treats a construction like \.{(E-15+y)}
as equivalent to `\.{(E+2)}', while also leaving `\.{(1E-15+y)}' and
`\.{(E-15+17*y)}' untouched. Consider also `\.{-15+17.5}' versus
`\.{-15+17..5}'. We shall not combine integers preceding or following
\.*, \./, \.{div}, \.{mod}, or \.{@@\&}. Note that if $y$ has been defined
to equal $-2$, we must expand `\.{x*y}' into `\.{x*(-2)}'; but `\.{x-y}'
can expand into `\.{x+2}' and we can even change `\.{x-y mod z}' to
@↑mod@>
`\.{x+2 mod z}' because \PASCAL\ has a nonstandard \&{mod} operation!
The following solution to these problems has been adopted: An array
|out←buf| contains characters that have been generated but not yet output,
and there are three pointers into this array. One of these, |out←ptr|, is
the number of characters currently in the buffer, and we will have
|1<=out←ptr<=line←length| most of the time. The second is |break←ptr|,
which is the largest value |<=out←ptr| such that we are definitely entitled
to end a line by outputting the characters |out←buf[1..(break←ptr-1)]|;
we will always have |break←ptr<=line←length|. Finally, |semi←ptr| is either
zero or the largest known value of a legal break after a semicolon on the
current line; we will always have |semi←ptr<=break←ptr|.
@<Globals...@>=
@!out←buf: array [0..out←buf←size] of ascii←code; {assembled characters}
@!out←ptr: 0..out←buf←size; {first available place in |out←buf|}
@!break←ptr: 0..out←buf←size; {last breaking place in |out←buf|}
@!semi←ptr: 0..out←buf←size; {last semicolon breaking place in |out←buf|}
@ Besides these two pointers, the output process is in one of several states:
\yskip\hang |num←or←id| means that the last item in the buffer is a number or
identifier, hence a blank space or line break must be inserted if the next
item is also a number or identifier.
\yskip\hang |unbreakable| means that the last item in the buffer was followed
by the \.{@@\&} operation that inhibits spaces between it and the next item.
\yskip\hang |sign| means that the last item in the buffer is to be followed
by \.+ or \.-, depending on whether |out←app| is positive or negative.
\yskip\hang |sign←val| means that the decimal equivalent of
$\leftv|out←val|\rightv$ should be appended to the buffer; if $out←val<0$,
it should be preceded by a minus sign, otherwise it should be preceded by
the character |out←sign| unless |out←sign=0|.
\yskip\hang |sign←val←sign| is like |sign←val|, but also append \.+ or \.-
afterwards, depending on whether |out←app| is positive or negative.
\yskip\hang |sign←val←val| is like |sign←val|, but also append the decimal
equivalent of |out←app| including its sign.
\yskip\hang |misc| means none of the above.
\yskip\noindent
For example, the output buffer and output state run through the following
sequence as we generate characters from `\.{(x-15+19-2)}':
$$\vbox{\halign{#\hfil&\quad\hfil#\hfil&\quad\hfil#\hfil&\quad
\hfil#\hfil&\quad\hfil#\hfil\cr
|out←buf|&|out←state|&|out←sign|&|out←val|&|out←app|\cr
\noalign{\vskip 3pt}
\.(&|misc|\cr
\.{(x}&|num←or←id|\cr
\.{(x}&|sign|&&&$-1$\cr
\.{(x}&|sign←val|&\.{"+"}&$-15$\cr
\.{(x}&|sign←val←sign|&\.{"+"}&$-15$&$+1$\cr
\.{(x}&|sign←val←val|&\.{"+"}&$-15$&$+19$\cr
\.{(x}&|sign←val←sign|&\.{"+"}&$+4$&$-1$\cr
\.{(x}&|sign←val←val|&\.{"+"}&$+4$&$-2$\cr
\.{(x+2)}&|misc|\cr}}$$
At each stage we have put as much into the buffer as possible without
knowing what is coming next.
In states |num←or←id|, |unbreakable|, and |misc| the last item in the buffer
lies between |break←ptr| and |out←ptr-1|, inclusive; in the other states we
have |break←ptr=out←ptr|.
The numeric values assigned to |num←or←id|, etc., have been chosen to
shorten some of the program logic; for example, the program makes use of
the fact that |sign+2=sign←val←sign|.
@d misc=0 {state associated with special characters}
@d num←or←id=1 {state associated with numbers and identifiers}
@d sign=2 {state associated with pending \.+ or \.-}
@d sign←val=num←or←id+2 {state associated with pending sign and value}
@d sign←val←sign=sign+2 {|sign←val| followed by another pending sign}
@d sign←val←val=sign←val+2 {|sign←val| followed by another pending value}
@d unbreakable=sign←val←val+1 {state associated with \.{@@\&}}
@<Globals...@>=
@!out←state:eight←bits; {current status of partial output}
@!out←val,@!out←app:integer; {pending values}
@!out←sign:ascii←code; {sign to use if appending |out←val>=0|}
@ During the output process, |line| will equal the number of the next line
to be output.
@<Initialize the output buffer@>=
out←state:=misc; out←ptr:=0; break←ptr:=0; semi←ptr:=0; out←buf[0]:=0; line:=1;
@ Here is a simple routine that is invoked when |out←ptr>line←length|
or when it is time to flush out the final line. The |flush←buffer| procedure
writes out the line up to the current |break←ptr| position, then moves the
remaining information to the front of |out←buf|.
@d check←break==if out←ptr>line←length then flush←buffer
@p procedure flush←buffer; {writes one line to output file}
var k:0..out←buf←size; {index into |out←buf|}
@!b:0..out←buf←size; {value of |break←ptr| upon entry}
begin b:=break←ptr;
if (semi←ptr<>0)and(out←ptr-semi←ptr<=line←length) then break←ptr:=semi←ptr;
for k:=1 to break←ptr do write(xchr[out←buf[k-1]]);
write←ln; incr(line);
if line mod 100 = 0 then print('.');
if break←ptr<out←ptr then
begin if out←buf[break←ptr]=" " then
begin incr(break←ptr); {drop space at break}
if break←ptr>b then b:=break←ptr;
end;
for k:=break←ptr to out←ptr-1 do out←buf[k-break←ptr]:=out←buf[k];
end;
out←ptr:=out←ptr-break←ptr; break←ptr:=b-break←ptr; semi←ptr:=0;
if out←ptr>line←length then
begin err←print('! Long line must be truncated'); out←ptr:=line←length;
@.Long line must be truncated@>
end;
end;
@ @<Empty the last line from the buffer@>=
if (out←state<>misc)or(out←buf[break←ptr]<>".") then
err←print('! Program didn''t end with period');
@.Program didn't end with period@>
break←ptr:=out←ptr; semi←ptr:=0; flush←buffer;
@ Another simple and useful routine appends the decimal equivalent of
a nonnegative integer to the output buffer.
@d app(#)==begin out←buf[out←ptr]:=#; incr(out←ptr); {appends a single character}
end
@p procedure app←val(@!v:integer); {puts |v| into buffer, assumes |v>=0|}
var k:0..out←buf←size; {index into |out←buf|}
begin k:=out←buf←size; {first we put the digits at the very end of |out←buf|}
repeat out←buf[k]:=v mod 10; v:=v div 10; decr(k);
until v=0;
repeat incr(k); app(out←buf[k]+"0");
until k=out←buf←size; {then we append them, most significant first}
end;
@ The output states are kept up to date by the output routines, which are
called |send←out|, |send←val|, and |send←sign|. The |send←out| procedure
has two parameters: $t$ tells the type of information being sent and
$v$ contains the information proper. Some information may also be passed
in the array |out←contrib|.
\yskip\hang If |t=misc| then $v$ is a character to be output.
\hang If |t=str| then $v$ is the length of a string or something like `\.{<>}'
in |out←contrib|.
\hang If |t=ident| then $v$ is the length of an identifier in |out←contrib|.
\hang If |t=frac| then $v$ is the length of a fraction and/or exponent in
|out←contrib|.
@d str=1 {|send←out| code for a string}
@d ident=2 {|send←out| code for an identifier}
@d frac=3 {|send←out| code for a fraction}
@<Glob...@>=
@!out←contrib:array[1..line←length] of ascii←code; {a contribution to |out←buf|}
@ A slightly subtle point in the following code is that the user may ask for
a |join| operation (i.e., \.{@@\&}) following whatever is being sent out. We will
see later that |join| is implemented in part by calling |send←out(frac,0)|.
@p procedure send←out(@!t:eight←bits; @!v:sixteen←bits); {outputs $v$ of type $t$}
label restart;
var k: 0..line←length; {index into |out←contrib|}
begin @<Get the buffer ready for appending the new information@>;
if t<>misc then for k:=1 to v do app(out←contrib[k])
else app(v);
check←break;
if (t=misc)and(v=";") then
begin semi←ptr:=out←ptr; break←ptr:=out←ptr;
end;
if t>=ident then out←state:=num←or←id {|t=ident| or |frac|}
else out←state:=misc {|t=str| or |misc|}
end;
@ Here is where the buffer states for signs and values collapse into simpler
states, because we are about to append something that doesn't combine with
the previous integer constants.
We use an ascii-code trick: Since |","-1="+"| and |","+1="-"|, we have
|","-c=@t sign of $c$@>|, when $\leftv c\rightv=1$.
@<Get the buffer ready...@>=
restart: case out←state of
num←or←id: if t<>frac then
begin break←ptr:=out←ptr;
if t=ident then app(" ");
end;
sign: begin app(","-out←app); check←break; break←ptr:=out←ptr;
end;
sign←val,sign←val←sign: begin @<Append \(|out←val| to buffer@>;
out←state:=out←state-2; goto restart;
end;
sign←val←val: @<Reduce |sign←val←val| to |sign←val| and |goto restart|@>;
misc: if t<>frac then break←ptr:=out←ptr;@;
othercases do←nothing {this is for |unbreakable| state}
endcases
@ @<Append \(|out←val|...@>=
if out←val<0 then app("-")
else if out←sign>0 then app(out←sign);
app←val(abs(out←val)); check←break;
@ @<Reduce |sign←val←val|...@>=
begin if (t=frac)or(@<Contribution is \.* or \./ or \.{DIV} or \.{MOD}@>) then
begin @<Append \(|out←val| to buffer@>;
out←sign:="+"; out←val:=out←app;
end
else out←val:=out←val+out←app;
out←state:=sign←val; goto restart;
end
@ @<Contribution is \.*...@>=
((t=ident)and(v=3)and@/
( ((out←contrib[1]="D")and(out←contrib[2]="I")and(out←contrib[3]="V")) or
((out←contrib[1]="M")and(out←contrib[2]="O")and(out←contrib[3]="D")) ))or@/
((t=misc)and((v="*")or(v="/")))
@ The following routine is called with $v=\pm1$ when a plus or minus sign is
appended to the output. It extends \PASCAL\ to allow repeated signs
(e.g., `\.{--}' is equivalent to `\.+'), rather than to give an error message.
The signs following `\.E' in real constants are treated as part of a fraction,
so they are not seen by this routine.
@p procedure send←sign(@!v:integer);
begin case out←state of
sign, sign←val←sign: out←app:=out←app*v;
sign←val:begin out←app:=v; out←state:=sign←val←sign;
end;
sign←val←val: begin out←val:=out←val+out←app; out←app:=v; out←state:=sign←val←sign;
end;
othercases begin break←ptr:=out←ptr; out←app:=v; out←state:=sign;
end
endcases;
end;
@ When a (signed) integer value is to be output, we call |send←val|.
Two consecutive values, although syntactically illegal, are silently
added together. In a situation like `\.{if x=y}' where $x$ has been defined
to equal $+3$, the output will be `\.{IF+3=Y}' rather than `\.{IF 3=Y}'.
@d bad←case=666 {this is a label used below}
@p procedure send←val(@!v:integer); {output the (signed) value $v$}
label bad←case, {go here if we can't keep $v$ in the output state}
exit;
begin case out←state of
num←or←id: begin @<If previous output was \.{DIV} or \.{MOD}, |goto bad←case|@>;
out←sign:=" "; out←state:=sign←val; out←val:=v; break←ptr:=out←ptr;
end;
misc: begin @<If previous output was \.* or \./, |goto bad←case|@>;
out←sign:=0; out←state:=sign←val; out←val:=v; break←ptr:=out←ptr;
end;
@t\4@>@<Handle cases of |send←val| when |out←state| contains a sign@>@;
othercases goto bad←case
endcases;@/
return;
bad←case: @<Append the decimal value of $v$, with parentheses if negative@>;
exit: end;
@ @<Handle cases of |send←val|...@>=
sign: begin out←sign:="+"; out←state:=sign←val; out←val:=out←app*v;
end;
sign←val: begin out←state:=sign←val←val; out←app:=v;
end;
sign←val←sign: begin out←state:=sign←val←val; out←app:=out←app*v;
end;
sign←val←val: begin out←val:=out←val+out←app; out←app:=v;
end;
@ @<If previous output was \.*...@>=
if (out←ptr=break←ptr+1)and((out←buf[break←ptr]="*")or(out←buf[break←ptr]="/"))
then goto bad←case
@ @<If previous output was \.{DIV}...@>=
if (out←ptr=break←ptr+3)or((out←ptr=break←ptr+4)and(out←buf[break←ptr]=" ")) then
if ((out←buf[out←ptr-3]="D")and(out←buf[out←ptr-2]="I")and
(out←buf[out←ptr-1]="V"))or @/
((out←buf[out←ptr-3]="M")and(out←buf[out←ptr-2]="O")and
(out←buf[out←ptr-1]="D")) then goto bad←case
@ @<Append the decimal value...@>=
if v>=0 then
begin if out←state=num←or←id then
begin break←ptr:=out←ptr; app(" ");
end;
app←val(v); check←break; out←state:=num←or←id;
end
else begin app("("); app("-"); app←val(-v); app(")"); check←break;
out←state:=misc;
end
@* The big output switch.
To complete the output process, we need a routine that takes the results
of |get←output| and feeds them to |send←out|, |send←val|, or |send←sign|.
This procedure `|send←the←output|' will be invoked just once, as follows:
@<Phase II: Output the contents of the compressed tables@>=
if text←link[0]=0 then print←nl('! No output was specified.')
@.No output was specified@>
else begin print←nl('Writing the output file...');@/
@<Initialize the output stacks@>;
@<Initialize the output buffer@>;
send←the←output;@/
@<Empty the last line...@>;
print←nl('Done.');
end
@ A many-way switch is used to send the output:
@d get←fraction=2 {this label is used below}
@p procedure send←the←output;
label get←fraction, {go here to finish scanning a real constant}
reswitch, continue;
var cur←char:eight←bits; {the latest character received}
@!k:0..line←length; {index into |out←contrib|}
@!j:0..max←bytes; {index into |byte←mem|}
@!n:integer; {number being scanned}
begin while stack←ptr>0 do
begin cur←char:=get←output;
reswitch: case cur←char of
0: do←nothing; {this case might arise if output ends unexpectedly}
@t\4@>@<Cases related to identifiers@>@;
@t\4@>@<Cases related to constants, possibly leading to
|get←fraction| or |reswitch|@>@;
"+","-": send←sign(","-cur←char);
@t\4@>@<Cases like \.{<>} and \.{:=}@>@;
"'": @<Send a string, |goto reswitch|@>;
@<Other printable characters@>: send←out(misc,cur←char);
@t\4@>@<Cases involving \.{@@\{} and \.{@@\}}@>@;
join: begin send←out(frac,0); out←state:=unbreakable;
end;
othercases err←print('! Can''t output ascii code ',cur←char:0)
@.Can't output ascii code n@>
endcases;@/
goto continue;
get←fraction: @<Special code to finish real constants@>;
continue: end;
end;
@ @<Cases like \.{<>}...@>=
and←sign: begin out←contrib[1]:="A"; out←contrib[2]:="N"; out←contrib[3]:="D";
send←out(ident,3);
end;
not←sign: begin out←contrib[1]:="N"; out←contrib[2]:="O"; out←contrib[3]:="T";
send←out(ident,3);
end;
set←element←sign: begin out←contrib[1]:="I"; out←contrib[2]:="N";
send←out(ident,2);
end;
or←sign: begin out←contrib[1]:="O"; out←contrib[2]:="R"; send←out(ident,2);
end;
left←arrow: begin out←contrib[1]:=":"; out←contrib[2]:="="; send←out(str,2);
end;
not←equal: begin out←contrib[1]:="<"; out←contrib[2]:=">"; send←out(str,2);
end;
less←or←equal: begin out←contrib[1]:="<"; out←contrib[2]:="="; send←out(str,2);
end;
greater←or←equal: begin out←contrib[1]:=">"; out←contrib[2]:="="; send←out(str,2);
end;
equivalence←sign: begin out←contrib[1]:="="; out←contrib[2]:="="; send←out(str,2);
end;
double←dot: begin out←contrib[1]:="."; out←contrib[2]:="."; send←out(str,2);
end;
@ Please don't ask how all of the following characters can actually get
through \.{TANGLE} outside of strings. It seems that |""""|, |"{"|,
and |"}"| cannot actually occur at this point of the program, but they have
been included just in case \.{TANGLE} changes.
If \.{TANGLE} is producing code for a \PASCAL\ compiler that uses `\.{(.}'
and `\.{.)}' instead of square brackets (e.g., on machines with {\mc EBCDIC}
code), one should remove |"["| and |"]"| from this list and put them into
the preceding module in the appropriate way. Similarly, some compilers
want `\.\↑' to be converted to `\.{@@}'.
@↑system dependencies@>@↑EBCDIC@>
@<Other printable characters@>=
"!","""","#","$","%","&","(",")","*",",","/",":",";","<","=",">","?",
"@@","[","\","]","↑","←","`","{","|","}"
@ Single-character identifiers represent themselves, while longer ones
appear in |byte←mem|. All must be converted to upper case,
with underlines removed. Extremely long identifiers must be chopped.
@d up←to(#)==#-24,#-23,#-22,#-21,#-20,#-19,#-18,#-17,#-16,#-15,#-14,
#-13,#-12,#-11,#-10,#-9,#-8,#-7,#-6,#-5,#-4,#-3,#-2,#-1,#
@<Cases related to identifiers@>=
"A",up←to("Z"): begin out←contrib[1]:=cur←char; send←out(ident,1);
end;
"a",up←to("z"): begin out←contrib[1]:=cur←char-@'40; send←out(ident,1);
end;
identifier: begin k:=0; j:=byte←start[cur←val];
while (k<max←id←length)and(j<byte←start[cur←val+1]) do
begin incr(k); out←contrib[k]:=byte←mem[j]; incr(j);
if out←contrib[k]>="a" then out←contrib[k]:=out←contrib[k]-@'40
else if out←contrib[k]="←" then decr(k);
end;
send←out(ident,k);
end;
@ After sending a string, we need to look ahead at the next character, in order
to see if there were two consecutive single-quote marks. Afterwards we go to
|reswitch| to process the next character.
@<Send a string...@>=
begin k:=1; out←contrib[1]:="'";
repeat if k<line←length then incr(k);
out←contrib[k]:=get←output;
until (out←contrib[k]="'")or(stack←ptr=0);
if k=line←length then err←print('! String too long');
@.String too long@>
send←out(str,k); cur←char:=get←output;
if cur←char="'" then out←state:=unbreakable;
goto reswitch;
end
@ In order to encourage portable software, \.{TANGLE} complains
if the constants get dangerously close to the largest value representable
on a 32-bit computer ($2↑{31}-1$).
@d digits=="0","1","2","3","4","5","6","7","8","9"
@<Cases related to constants...@>=
digits: begin n:=0;
repeat if n>=@'1463146314 then err←print('! Constant too big')
@.Constant too big@>
else n:=10*n+cur←char-"0";
cur←char:=get←output;
until (cur←char>"9")or(cur←char<"0");
send←val(n); k:=0;
if cur←char="e" then cur←char:="E";
if cur←char="E" then goto get←fraction
else goto reswitch;
end;
octal: begin n:=0; cur←char:="0";
repeat if n>=@'2000000000 then err←print('! Constant too big')
else n:=8*n+cur←char-"0";
cur←char:=get←output;
until (cur←char>"7")or(cur←char<"0");
send←val(n); goto reswitch;
end;
number: send←val(cur←val);
".": begin k:=1; out←contrib[1]:="."; cur←char:=get←output;
if cur←char="." then
begin out←contrib[2]:="."; send←out(str,2);
end
else if (cur←char>="0")and(cur←char<="9") then goto get←fraction
else begin send←out(misc,"."); goto reswitch;
end;
end;
@ The following code appears at label `|get←fraction|', when we want to
scan to the end of a real constant. The first $k$ characters of a fraction
have already been placed in |out←contrib|, and |cur←char| is the next character.
@<Special code...@>=
repeat if k<line←length then incr(k);
out←contrib[k]:=cur←char; cur←char:=get←output;
if (out←contrib[k]="E")and((cur←char="+")or(cur←char="-")) then
begin if k<line←length then incr(k);
out←contrib[k]:=cur←char; cur←char:=get←output;
end
else if cur←char="e" then cur←char:="E";
until (cur←char<>"E")and((cur←char<"0")or(cur←char>"9"));
if k=line←length then err←print('! Fraction too long');
@.Fraction too long@>
send←out(frac,k); goto reswitch
@ Some \PASCAL\ compilers do not recognize comments in braces, so the
comments must be delimited by `\.{(*}' and `\.{*)}'.
@↑system dependencies@>
In such cases the statement `|send←out(misc,"{")|' that appears here
should be replaced by `\!|begin out←contrib[1]:="("; out←contrib[2]:="*";
send←out(str,2); end|', and a similar change should be made to
`|send←out(misc,"}")|'.
@<Cases involving \.{@@\{} and \.{@@\}}@>=
begin←comment: begin if brace←level=0 then send←out(misc,"{")
else send←out(misc,"[");
incr(brace←level);
end;
end←comment: if brace←level>0 then
begin decr(brace←level);
if brace←level=0 then send←out(misc,"}")
else send←out(misc,"]");
end
else err←print('! Extra @@}');
@.Extra \at@>
module←number: if brace←level=0 then
begin send←out(misc,"{"); send←val(cur←val); send←out(misc,"}");
end
else begin send←out(misc,"["); send←val(cur←val); send←out(misc,"]");
end;
@* Introduction to the input phase.
We have now seen that \.{TANGLE} will be able to output the full \PASCAL\
program, if we can only get that program into the byte memory in the proper
format. The input process is something like the output process in reverse,
since we compress the text as we read it in and we expand it as we write it out.
There are three main input routines. The most interesting is the one that gets
the next token of a \PASCAL\ text; the other two are used to scan rapidly past
\TEX\ text in the \.{WEB} source code. One of the latter routines will jump to
the next token that starts with `\.{@@}', and the other skips to the end
of a \PASCAL\ comment.
@ But first we need to consider the low-level routine that takes care of
updating page and line numbers for error messages. This routine also
makes sure that the input ends with an end-of-page signal. The
conventions of \TEX's input routine are used in simplified form: When
|line=0|, it is time to read a new page. After a line has been input,
either |buffer[limit]| is a |carriage←return|, on a normal line, or we
have |limit=0| and |buffer[0]=form←feed|, in which case this is the line
that ends a page. The value of |limit| is always strictly less than
|buf←size|, so it is possible to refer to |buffer[limit+1]| without
overstepping the bounds of the array.
@<Globals...@>=
@!page:sixteen←bits; {the number of the page currently being read}
@!line:sixteen←bits; {the number of the current line on the current page}
@!limit:0..buf←size; {the last character position occupied in the buffer}
@!loc:0..buf←size; {the next character position to be read from the buffer}
@!input←has←ended: boolean; {if |true|, there is no more input}
@ @<Initialize the input system@>=
open←input;
page:=0; line:=0; limit:=0; loc:=1; buffer[0]:=" ";
input←has←ended:=false;
@ The |get←line| procedure is called when |loc>limit|; it puts the next
line of input into the buffer and updates the other variables appropriately.
A carriage return at the end of a line is changed to a space.
@p procedure get←line; {inputs the next line}
begin if buffer[0]=form←feed then line:=0;
if input←ln then {not end of file}
begin if line=0 then {first line of page}
begin incr(page);@/
@<Special check for file directory page@>;
end;
if buffer[limit]=carriage←return then buffer[limit]:=" ";
end
else if buffer[0]<>form←feed then {insert page mark at end of file}
begin limit:=0; buffer[0]:=form←feed;
end
else input←has←ended:=true; {note that page mark is still present}
incr(line); loc:=0;
end;
@ The `E' editor on Stanford's {\sc SAIL} computer, where the present version
of \.{TANGLE} was developed, makes up a special first page called the `file
directory' for the files it works with.
This first page is recognizable with sufficiently high
probability by the fact that its first line has length 29 and its first
and ninth characters are respectively `\.C' and `\.{\char'26}'. So the Stanford
version of \.{TANGLE} has special code to skip past all but the page mark
of such a first page:
@<Special check for file directory page@>=
stanford if (page=1)and(limit=29) then
if (buffer[0]="C")and(buffer[8]=@'26) then
repeat if input←ln then do←nothing
else begin limit:=0; buffer[0]:=form←feed;
end;
until buffer[0]=form←feed
drofnats
@ Important milestones are reached during the input phase when certain
control codes are sensed, or when a page ends.
Control codes in \.{WEB} begin with `\.{@@}', and the next character
identifies the code. Some of these are of interest only to \.{WEAVE},
so \.{TANGLE} ignores them; the others are converted by \.{TANGLE} into
internal code numbers by the |control←code| function below. The ordering
of these internal code numbers has been chosen to simplify the program logic;
larger numbers are given to the control codes that denote more significant
milestones.
@d ignore=0 {control code of no interest to \.{TANGLE}}
@d TEX←string=@'203 {control code for `\.{@@t}', `\.{@@\↑}', and `\.{@@.}'}
@d format=@'204 {control code for `\.{@@f}'}
@d definition=@'205 {control code for `\.{@@d}'}
@d begin←pascal=@'206 {control code for `\.{@@p}'}
@d module←name=@'207 {control code for `\.{@@<}'}
@d page←end=@'210 {control code for end-of-page}
@d new←module=@'211 {control code for `\.{@@ }' and `\.{@@*}'}
@p function control←code(@!c:ascii←code):eight←bits; {convert $c$ after \.{@@}}
begin case c of
"@@": control←code:="@@"; {`quoted' at sign}
"'": control←code:=octal; {precedes octal constant}
" ",tab←mark: control←code:=new←module; {beginning of a new module}
"*": begin print('*'); {print a progress report}
control←code:=new←module; {beginning of a new module}
end;
"D","d": control←code:=definition; {macro definition}
"F","f": control←code:=format; {format definition}
"{": control←code:=begin←comment; {begin-comment delimiter}
"}": control←code:=end←comment; {end-comment delimiter}
"P","p": control←code:=begin←pascal; {\PASCAL\ text in unnamed module}
"T","t","↑",".",":": control←code:=TEX←string; {\.{@@t...@@>} to be ignored}
"&": control←code:=join; {concatenate two tokens}
"<": control←code:=module←name; {beginning of a module name}
othercases control←code:=ignore {ignore all other cases}
endcases;
end;
@ The |skip←ahead| procedure reads through the input at fairly high speed
until finding the next non-ignorable control code, which it returns.
@p function skip←ahead:eight←bits; {skip to next control code}
label done;
var c:eight←bits; {control code found}
begin loop begin if loc>limit then
begin get←line;
if buffer[0]=form←feed then
begin loc:=1; c:=page←end; goto done;
end;
end;
buffer[limit+1]:="@@";
while buffer[loc]<>"@@" do incr(loc);
if loc<=limit then
begin loc:=loc+2; c:=control←code(buffer[loc-1]);
if (c<>ignore)or(buffer[loc-1]=">") then goto done;
end;
end;
done: skip←ahead:=c;
end;
@ The |skip←comment| procedure reads through the input at somewhat high speed
until finding the first unmatched right brace or until coming to the end
of a page. It ignores characters following `\.\\' characters, since all
braces that aren't nested are supposed to be hidden in that way. For
example, consider the process of skipping the first comment below,
where the string containing the right brace has been typed as \.{\`\\.\\\}\'}
in the \.{WEB} file.
@p procedure skip←comment; {skips to next unmatched `\.\}'}
label exit;
var bal:eight←bits; {excess of left braces}
@!c:ascii←code; {current character}
begin bal:=0;
loop@+ begin if loc>limit then
begin get←line;
if buffer[0]=form←feed then
begin err←print('! Page ended in mid-comment');
@.Page ended in mid-comment@>
loc:=1; return;
end;
end;
c:=buffer[loc]; incr(loc);
@<Do special things when |c="@@", "\", "{", "}"|; |return| at end@>;
end;
exit:end;
@ @<Do special things when |c="@@"...@>=
if c="@@" then
begin c:=buffer[loc];
if (c<>" ")and(c<>tab←mark)and(c<>"*") then incr(loc)
else begin err←print('! Module ended in mid-comment');
@.Module ended in mid-comment@>
decr(loc); return;
end
end
else if (c="\")and(buffer[loc]<>"@@") then incr(loc)
else if c="{" then incr(bal)
else if c="}" then
begin if bal=0 then return;
decr(bal);
end
@* Inputting the next token.
As stated above, \.{TANGLE}'s most interesting input procedure is the
|get←next| routine that inputs the next token. However, the procedure
isn't especially difficult.
In most cases the tokens output by |get←next| have the form used in
replacement texts, except that two-byte tokens are not produced.
An identifier that isn't one letter long is represented by the
output `|identifier|', and in such a case the global variables
|id←first| and |id←loc| will have been set to the appropriate values
needed by the |id←lookup| procedure. A string that begins with a
double-quote is also considered an |identifier|, and in such a case
the global variable |double←chars| will also have been set appropriately.
Control codes produce the corresponding output of the |control←code|
function above; and if that code is |module←name|, the value of |cur←module|
will point to the |byte←start| entry for that module name.
@<Globals...@>=
@!cur←module: name←pointer; {name of module just scanned}
@ At the top level, |get←next| is a multi-way switch based on the next
character in the input buffer.
@p function get←next:eight←bits; {produces the next input token}
label restart,done;
var c:eight←bits; {the current character}
@!d:eight←bits; {the next character}
@!j,@!k:0..longest←name; {indices into |module|}
begin restart: if loc>limit then get←line;
c:=buffer[loc]; incr(loc);
case c of
"A",up←to("Z"),"a",up←to("z"): @<Get an identifier@>;
"""": @<Get a preprocessed string@>;
"@@": @<Get control code and possible module name@>;
@t\4@>@<Compress two-symbol combinations like `\.{:=}'@>@;
" ",tab←mark: goto restart; {ignore spaces and tabs}
"{": begin skip←comment; goto restart;
end;
form←feed: c:=page←end;
othercases do←nothing
endcases;
debug if trouble←shooting then debug←help;@;@+gubed@/
get←next:=c;
end;
@ Note that the following code substitutes \.{@@\{} and \.{@@\}} for the
respective combinations `\.{(*}' and `\.{*)}'. Explicit braces should be used
for \TEX\ comments in \PASCAL\ text.
@d compress(#)==begin c:=#; incr(loc); end
@<Compress two-symbol...@>=
".": if buffer[loc]="." then compress(double←dot)
else if buffer[loc]=")" then compress("]");
":": if buffer[loc]="=" then compress(left←arrow);
"=": if buffer[loc]="=" then compress(equivalence←sign);
">": if buffer[loc]="=" then compress(greater←or←equal);
"<": if buffer[loc]="=" then compress(less←or←equal)
else if buffer[loc]=">" then compress(not←equal);
"(": if buffer[loc]="*" then compress(begin←comment)
else if buffer[loc]="." then compress("[");
"*": if buffer[loc]=")" then compress(end←comment);
@ We have to look at the preceding character to make sure this isn't part
of a real constant, before trying to find an identifier starting with
`\.e' or `\.E'.
@<Get an identifier@>=
begin if ((c="e")or(c="E"))and(loc>1) then
if (buffer[loc-2]<="9")and(buffer[loc-2]>="0") then c:=0;
if c<>0 then
begin decr(loc); id←first:=loc;
repeat incr(loc); d:=buffer[loc];
until ((d<"0")or((d>"9")and(d<"A"))or((d>"Z")and(d<"a"))or(d>"z")) and (d<>"←");
if loc>id←first+1 then
begin c:=identifier; id←loc:=loc;
end;
end
else c:="E"; {exponent of a real constant}
end
@ A string that starts and ends with double-quote marks is converted into
an identifier that behaves like a numeric macro by means of the following
piece of the program.
@↑preprocessed strings@>
@<Get a preprocessed string@>=
begin double←chars:=0; id←first:=loc-1;
repeat d:=buffer[loc]; incr(loc);
if (d="""")or(d="@@") then
if buffer[loc]=d then
begin incr(loc); d:=0; incr(double←chars);
end
else begin if d="@@" then err←print('! Double @@ sign missing')
@.Double {\at} sign missing@>
end
else if loc>limit then
begin err←print('! String constant didn''t end'); d:="""";
@.String constant didn't end@>
end;
until d="""";
id←loc:=loc-1; c:=identifier;
end
@ After an \.{@@} sign has been scanned, the next character tells us
whether there is more work to do.
@<Get control code and possible module name@>=
begin c:=control←code(buffer[loc]); incr(loc);
if c=ignore then goto restart
else if c=module←name then
@<Scan the \(module name and make |cur←module| point to it@>
else if c=TEX←string then
begin repeat c:=skip←ahead;
until c<>"@@";
if buffer[loc-1]<>">" then
err←print('! Improper @@ within control text');
@.Improper {\at} within control text@>
goto restart;
end;
end
@ @<Scan the \(module name...@>=
begin @<Put module name into |module[1..k]|@>;
if k>3 then
begin if (module[k]=".")and(module[k-1]=".")and(module[k-2]=".") then
cur←module:=prefix←lookup(k-3)
else cur←module:=mod←lookup(k);
end
else cur←module:=mod←lookup(k);
end
@ Module names are placed into the |module| array with consecutive spaces,
tabs, and carriage-returns replaced by single spaces. There will be no
spaces at the beginning or the end. (We set |module[0]:=" "| to facilitate
this, since the |mod←lookup| routine uses |module[1]| as the first
character of the name.)
@<Set init...@>=module[0]:=" ";
@ @<Put module name...@>=
k:=0;
loop@+ begin if loc>limit then
begin get←line;
if buffer[0]=form←feed then
begin err←print('! Page ended in module name');
@.Page ended in module name@>
loc:=1; goto done;
end;
end;
d:=buffer[loc];
@<If end of name, |goto done|@>;
incr(loc); if k<longest←name-1 then incr(k);
if (d=" ")or(d=tab←mark) then
begin d:=" "; if module[k-1]=" " then decr(k);
end;
module[k]:=d;
end;
done: @<Check for overlong name@>;
if (module[k]=" ")and(k>0) then decr(k);
@ @<If end of name,...@>=
if d="@@" then
begin d:=buffer[loc+1];
if d=">" then
begin loc:=loc+2; goto done;
end;
if (d=" ")or(d=tab←mark)or(d="*") then
begin err←print('! Module name didn''t end'); goto done;
@.Module name didn't end@>
end;
incr(k); module[k]:="@@"; incr(loc); {now |d=buffer[loc]| again}
end
@ @<Check for overlong name@>=
if k>=longest←name-2 then
begin print←nl('! Module name too long: ');
@.Module name too long@>
for j:=1 to 25 do print(xchr[module[j]]);
print('...');
end
@* Scanning a numeric definition.
When \.{TANGLE} looks at the \PASCAL\ text following the `\.=' of a numeric
macro definition, it calls on the precedure |scan←numeric(p)|, where $p$
points to the name that is to be defined. This procedure evaluates the
right-hand side, which must consist entirely of integer constants and
defined numeric macros connected with \.+ and \.- signs (no parentheses).
It also sets the global variable |next←control| to the control code that
terminated this definition.
A definition ends with the control codes |definition|, |format|, |module←name|,
|begin←pascal|, |new←module|, and |page←end|, all of which can be recognized
by the fact that they are the largest values |get←next| can return.
@d end←of←definition(#)==(#>=format) {is |#| a control code ending a definition?}
@<Global...@>=
@!next←control:eight←bits; {control code waiting to be acted upon}
@ The evaluation of a numeric expression makes use of two variables called the
|accumulator| and the |next←sign|. At the beginning, |accumulator| is zero and
|next←sign| is $+1$. When a \.+ or \.- is scanned, |next←sign| is multiplied
by the value of that sign. When a numeric value is scanned, it is multiplied
|next←sign| and added to the |accumulator|, then |next←sign| is reset to $+1$.
@p procedure scan←numeric(@!p:name←pointer); {defines numeric macros}
label reswitch, done;
var accumulator:integer; {accumulates sums}
@!next←sign:-1..+1; {sign to attach to next value}
@!q:name←pointer; {points to identifiers being evaluated}
@!val:integer; {constants being evaluated}
procedure add←in(@!v:integer); {do this when a new value comes in}
begin accumulator:=accumulator+next←sign*v; next←sign:=+1;
end;
begin @<Set \(|accumulator| to the value of the right-hand side@>;
if abs(accumulator)>=@'100000 then
begin err←print('! Value too big: ',accumulator:0); accumulator:=0;
@.Value too big@>
end;
equiv[p]:=accumulator+@'100000; {name $p$ now is defined to equal |accumulator|}
end;
@ @<Set \(|accumulator| to the value of the right-hand side@>=
accumulator:=0; next←sign:=+1;
loop@+ begin next←control:=get←next;
reswitch: case next←control of
digits: begin @<Set |val| to value of decimal constant, and
set |next←control| to the following token@>;
add←in(val); goto reswitch;
end;
octal: begin @<Set |val| to value of octal constant, and
set |next←control| to the following token@>;
add←in(val); goto reswitch;
end;
identifier: begin q:=id←lookup(normal);
if ilk[q]<>numeric then
begin next←control:="*"; goto reswitch; {leads to error}
end;
add←in(equiv[q]-@'100000);
end;
"+": do←nothing;
"-": next←sign:=-next←sign;
format, definition, module←name, begin←pascal, page←end,
new←module: goto done;
";": err←print('! Omit semicolon in numeric definition');
@.Omit semicolon in numeric def...@>
othercases @<Signal error, flush rest of the definition@>
endcases;
end;
done:
@ @<Signal error, flush rest...@>=
begin err←print('! Improper numeric definition will be flushed');
@.Improper numeric definition...@>
repeat next←control:=skip←ahead
until end←of←definition(next←control);
if next←control=module←name then
begin {we want to scan the module name too}
loc:=loc-2; next←control:=get←next;
end;
accumulator:=0; goto done;
end
@ @<Set |val| to value of decimal...@>=
val:=0;
repeat val:=10*val+next←control-"0"; next←control:=get←next;
until (next←control>"9")or(next←control<"0");
@ @<Set |val| to value of octal...@>=
val:=0; next←control:="0";
repeat val:=8*val+next←control-"0"; next←control:=get←next;
until (next←control>"7")or(next←control<"0");
@* Scanning a macro definition.
The rules for generating the replacement texts corresponding to simple
macros, parametric macros, and \PASCAL\ texts of a module are almost
identical, so a single procedure is used for all three cases. The
differences are that
\yskip\item{a)} The sign |#| denotes a parameter only when it appears
outside of strings in a parametric macro; otherwise it stands for the
ascii character |#|. (This is not used in standard \PASCAL, but some
\PASCAL s allow, for example, `\.{/\#}' after a certain kind of file name.)
\item{b)}Module names are not allowed in simple macros or parametric macros;
in fact, the appearance of a module name terminates such macros and denotes
the name of the current module.
\item{c)}The symbols \.{@@d} and \.{@@f} and \.{@@p} are not allowed after
module names, while they terminate macro definitions.
@ Therefore there is a procedure |scan←repl| whose parameter $t$ specifies
either |simple| or |parametric| or |module←name|. After |scan←repl| has
acted, |cur←repl←text| will point to the replacement text just generated, and
|next←control| will contain the control code that terminated the activity.
@<Globals...@>=
@!cur←repl←text:text←pointer; {replacement text formed by |scan←repl|}
@ @p procedure scan←repl(@!t:eight←bits); {creates a replacement text}
label continue, done, found;
var a:sixteen←bits; {the current token}
@!b:ascii←code; {a character from the buffer}
@!bal:eight←bits; {left parentheses minus right parentheses}
begin bal:=0;
loop@+ begin continue: a:=get←next;
case a of
"(": incr(bal);
")": if bal=0 then err←print('! Extra )')
@.Extra )@>
else decr(bal);
"'": @<Copy a string from the buffer to |tok←mem|@>;
"#": if t=parametric then a:=param;
@t\4@>@<In cases that $a$ is a non-ascii token (|identifier|,
|module←name|, etc.), either process it and change $a$ to a byte
that should be stored, or |goto continue| if $a$ should be ignored,
or |goto done| if $a$ signals the end of this replacement text@>@;
othercases do←nothing
endcases;@/
app←repl(a); {store $a$ in |tok←mem|}
end;
done: next←control:=a;
@<Make sure the parentheses balance@>;
if text←ptr=max←texts then overflow('text');
cur←repl←text:=text←ptr; incr(text←ptr); tok←start[text←ptr]:=tok←ptr;
end;
@ @<Make sure the parentheses balance@>=
if bal>0 then
begin err←print('! Missing ',bal:0,' )');
@.Missing n )@>
while bal>0 do
begin app←repl(")"); decr(bal);
end;
end
@ @<In cases that $a$ is...@>=
identifier: begin a:=id←lookup(normal); app←repl((a div @'400)+@'200);
a:=a mod @'400;
end;
module←name: if t<>module←name then goto done
else begin app←repl((cur←module div @'400)+@'250);
a:=cur←module mod @'400;
end;
definition, format, begin←pascal: if t<>module←name then goto done
else begin err←print('! @@',xchr[buffer[loc-1]],
@.\at p is ignored in PASCAL text@>
' is ignored in PASCAL text'); goto continue;
end;
page←end, new←module: goto done;
@ @<Copy a string...@>=
begin b:="'";
loop@+ begin app←repl(b);
if b="@@" then
if buffer[loc]="@@" then incr(loc) {store only one \.{@@}}
else err←print('! You should double @@ signs in strings');
@.You should double {\at} signs@>
if loc=limit then
begin err←print('! String didn''t end');
@.String didn't end@>
buffer[loc]:="'"; buffer[loc+1]:=0;
end;
b:=buffer[loc]; incr(loc);
if b="'" then
begin if buffer[loc]<>"'" then goto found
else begin incr(loc); app←repl("'");
end;
end;
end;
found: end {now |a| holds the final |"'"| that will be stored}
@ The following procedure is used to define a simple or parametric macro,
just after the `\.{==}' of its definition has been scanned.
@p procedure define←macro(@!t:eight←bits);
var p:name←pointer; {the identifier being defined}
begin p:=id←lookup(t); scan←repl(t);@/
equiv[p]:=cur←repl←text; text←link[cur←repl←text]:=0;
end;
@* Scanning a module.
The |scan←module| procedure starts when `\.{@@ }' has been sensed in the
input, and it proceeds until the end of that module, i.e., until the
end of the page or the next `\.{@@ }'. It uses |module←count| to keep
track of the current module number; with luck, \.{WEAVE} and \.{TANGLE}
will both assign the same numbers to modules.
@<Globals...@>=
@!module←count:0..@'27777; {the current module number}
@ @p procedure scan←module;
label done, exit, continue;
var p:name←pointer; {module name for the current module}
begin incr(module←count);
@<Scan the \(definition part of the current module@>;
@<Scan the \PASCAL\ part of the current module@>;
exit: end;
@ @<Scan the \(definition part...@>=
next←control:=0;
loop@+ begin continue: while next←control<=format do
begin next←control:=skip←ahead;
if next←control=module←name then
begin {we want to scan the module name too}
loc:=loc-2; next←control:=get←next;
end;
end;
if next←control<>definition then goto done;
next←control:=get←next; {get identifier name}
if next←control<>identifier then
begin err←print('! Definition flushed, must start with ',
@.Definition flushed...@>
'identifier of length > 1'); goto continue;
end;
next←control:=get←next; {get token after the identifier}
if next←control="=" then
begin scan←numeric(id←lookup(numeric)); goto continue;
end
else if next←control=equivalence←sign then
begin define←macro(simple); goto continue;
end
else @<If the next text is `|(#)==|', call |define←macro|
and |goto continue|@>;
err←print('! Definition flushed since it starts badly');
@.Definition flushed...@>
end;
done:
@ @<If the next text is `|(#)==|'...@>=
if next←control="(" then
begin next←control:=get←next;
if next←control="#" then
begin next←control:=get←next;
if next←control=")" then
begin next←control:=get←next;
if next←control="=" then
begin err←print('! Use == for macros');
@.Use == for macros@>
next←control:=equivalence←sign;
end;
if next←control=equivalence←sign then
begin define←macro(parametric); goto continue;
end;
end;
end;
end;
@ @<Scan the \PASCAL...@>=
case next←control of
begin←pascal:p:=0;
module←name: begin p:=cur←module;
@<Check that |=| or |==| follows this module name, otherwise |return|@>;
end;
othercases return
endcases;@/
@<Insert the module number into |tok←mem|@>;
scan←repl(module←name); {now |cur←repl←text| points to the replacement text}
@<Update the data structure so that the replacement text is accessible@>;
@ @<Check that |=|...@>=
repeat next←control:=get←next;
until next←control<>"+"; {allow optional `\.{+=}'}
if (next←control<>"=")and(next←control<>equivalence←sign) then
begin err←print('! PASCAL text flushed, = sign is missing');
@.PASCAL text flushed...@>
repeat next←control:=skip←ahead;
until next←control>=page←end;
return;
end
@ @<Insert the module number...@>=
store←two←bytes(@'150000+module←count); {|@'150000=@'320*@'400|}
@ @<Update the data...@>=
if p=0 then {unnamed module}
begin text←link[last←unnamed]:=cur←repl←text; last←unnamed:=cur←repl←text;
end
else if equiv[p]=0 then equiv[p]:=cur←repl←text {first module of this name}
else begin p:=equiv[p];
while text←link[p]<module←flag do p:=text←link[p]; {find end of list}
text←link[p]:=cur←repl←text;
end;
text←link[cur←repl←text]:=module←flag; {mark this replacement text as a nonmacro}
@* Debugging.
The \PASCAL\ debugger with which \.{TANGLE} was developed allows breakpoints
to be set, and variables can be read and changed, but procedures cannot be
executed. Therefore a `|debug←help|' procedure has been inserted in the main
loops of each phase of the program; when |ddt| and |dd| are set to appropriate
values, symbolic printouts of various tables will appear.
The idea is to set a breakpoint inside the |debug←help| routine,
at the place of the asterisks below.
Then when |debug←help| is to be activated, set |trouble←shooting|
equal to |true|. After stopping at the breakpoint, the |debug←help|
routine will prompt you for values of |ddt| and |dd|, discontinuing
this when |ddt<=0|; thus you type $2n+1$ integers, ending with zero or
a negative number, after which you return to the breakpoint (if you typed
zero) or you exit the routine (if you typed a negative value).
Another global variable, |debug←cycle|, can be used to skip silently
past calls on |debug←help|. If you set |debug←cycle>1|, the program stops
only every |debug←cycle| times |debug←help| is called; however,
any error stop will set |debug←cycle| to zero.
@<Globals...@>=
debug@!trouble←shooting:boolean; {is |debug←help| wanted?}
@!ddt:sixteen←bits; {operation code for the |debug←help| routine}
@!dd:sixteen←bits; {operand in procedures performed by |debug←help|}
@!debug←cycle:integer; {threshold for |debug←help| stopping}
@!debug←skipped:integer; {we have skipped this many |debug←help| calls}
gubed
@ @↑system dependencies@>
@<Set init...@>=
debug trouble←shooting:=true; debug←cycle:=1; debug←skipped:=0;@/
trouble←shooting:=false; debug←cycle:=99999; {these are for when it almost works}
gubed
@ @↑system dependencies@>
@d breakpoint=888 {place where a breakpoint is desirable}
@p debug procedure debug←help; {routine to display various things}
label breakpoint,exit;
var k:sixteen←bits; {index into various arrays}
begin incr(debug←skipped);
if debug←skipped<debug←cycle then return;
debug←skipped:=0;
breakpoint:@{@/
'*************breakpoint*************';@/
'***********for**debugging***********'@}@;
loop@+ begin write(tty,'#'); read(tty,ddt);
if ddt<0 then return
else if ddt=0 then goto breakpoint;
read(tty,dd);
case ddt of
1: print←id(dd);
2: print←repl(dd);
3: for k:=1 to dd do print(xchr[buffer[k]]);
4: for k:=1 to dd do print(xchr[module[k]]);
5: for k:=1 to out←ptr do print(xchr[out←buf[k]]);
6: for k:=1 to dd do print(xchr[out←contrib[k]]);
othercases print('?')
endcases;
end;
exit:end;
gubed
@* The main program.
We have defined plenty of procedures, and it is time to put the last
pieces of the puzzle in place. Here is where \.{TANGLE} starts, and where
it ends.
@↑system dependencies@>
@p begin initialize;
@<Initialize the input system@>;
@<Phase I: Read all the user's text and compress it into |tok←mem|@>;
stat max←tok←ptr:=tok←ptr;@+tats@;@/
@<Phase II:...@>;
end←of←TANGLE:
if string←ptr>128 then
print←nl(string←ptr-128:0, ' strings written to string pool file.');
stat @<Print statistics about memory usage@>;@+tats@;@/
@t\4@>{here files should be closed if the operating system requires it}
end.
@ @<Phase I:...@>=
phase←one:=true;
module←count:=0;
repeat next←control:=skip←ahead;
while next←control=new←module do scan←module;
until input←has←ended;
phase←one:=false;
@ @<Print statistics about memory usage@>=
print←nl('Memory usage statistics:');
print←nl(name←ptr:0, ' names, ', text←ptr:0, ' replacement texts;');
print←nl(byte←ptr:0, ' bytes, ', max←tok←ptr:0, ' tokens.');
@* Index.
Here is a cross-reference table for the \.{TANGLE} processor.
All modules in which an identifier is
used are listed with that identifier, except that reserved words are
indexed only when they appear in format definitions, and the appearances
of identifiers in module names are not indexed. Underlined entries
correspond to where the identifier was declared. Error messages and
a few other things like ``ascii code'' are indexed here too.